I'm trying to use '%' in JavaScript, but it's not working. I need to understand why.
This is my moveTo(x, y) function. Where x and y are either -1, 0, or 1. The player will only move between -1 and 1 up to player.speed distance at a time. Speed = 0.05 and remains constant throughout the game. debug is a temporary global variable used to print out on the screen when there is an error.
The comments are the results of what is on the debug screen when the player cannot move any further. The furthest the player should be able to move is -1 or 1 in any direction, but in this JavaScript code, they move between -0.2 and 0.2.
// src(0.2, 0, 0.05) -> dest(1, 0) GOOD
debug = "src(" + this.x + ", " + this.y + ", " + this.speed + ")";
debug += " -> dest(" + x + ", " + y + ")";
x = this.x + x * this.speed;
y = this.y + y * this.speed;
// calc[0.0125, 0] -> dest(0.25, 0) GOOD
debug += " -> calc[" + (x * this.speed) + ", " + (y * this.speed) + "]";
debug += " -> dest(" + x + ", " + y + ")";
x = x - (x % this.speed);
y = y - (y % this.speed);
// calc[0, 0] -> dest(0.2, 0) BAD!
debug += " -> calc[" + (x % this.speed) + ", " + (y % this.speed) + "]";
debug += " -> dest(" + x + ", " + y + ")";
this.x = (x < -1)? -1 : (x > 1)? 1 : x;
this.y = (y < -1)? -1 : (y > 1)? 1 : y;
// result (0.2, 0)
debug += " -> result(" + this.x + ", " + this.y + ")";
The problem occurs on line 11 and 12
As you can see from the debug x % speed (or 0.25 % 0.05) = 0
!However x - x % speed (or 0.25 - 0) = 0.2
I have tried:
- x -= x % this.speed;
- x = x - x % this.speed;
- x = x - (x % this.speed);
but nothing will let the player go past -0.2 or 0.2.