1

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.

  • I get the sense that `speed === 0.05`, and not zero as you say – smac89 Apr 18 '18 at 05:55
  • 1
    Open a nodejs shell and type `0.25 % 0.05` – smac89 Apr 18 '18 at 05:57
  • Maybe it's because I've been awake too long, but this code is a nightmare to follow. Can you narrow down your problem to the specific issue? – Brad Apr 18 '18 at 05:58
  • I can see where your confusion lies lol. Typing `0.25 / 0.05` gives `5` but doing the modulos gives a remainder of `0.05`. MIND BLOWN! – smac89 Apr 18 '18 at 05:59
  • Thanks smac89, I'm not sure why but multiplying my values by 100, then using the modulus operator worked. I understood comparing the values would be inaccurate due to floating-point math, but I still don't understand why modulus would have a problem. Its seems so weird – Daemon Hylix Apr 18 '18 at 06:25

1 Answers1

0

Remainder (%) is binary operator. Returns the integer remainder of dividing the two operands.

So if you want to use % operator, you should convert your param to integer.

Toraaa
  • 145
  • 2
  • 10
  • I don't think that's true about modulos returning the integer remainder. According to what I've tried, it seems to be returning the fractional part as well just fine – smac89 Apr 18 '18 at 06:08
  • my opinion is that it is not suitable for float :) – Toraaa Apr 18 '18 at 06:20