【发布时间】:2018-04-18 05:51:51
【问题描述】:
我正在尝试在 JavaScript 中使用 '%',但它不起作用。我需要了解原因。
这是我的 moveTo(x, y) 函数。其中 x 和 y 为 -1、0 或 1。玩家一次只能在 -1 和 1 之间移动到 player.speed 距离。速度 = 0.05 并且在整个游戏中保持不变。 debug 是一个临时全局变量,用于在出现错误时在屏幕上打印出来。
cmets 是当玩家无法进一步移动时调试屏幕上显示的结果。玩家在任何方向上应该能够移动的最远距离是 -1 或 1,但在这段 JavaScript 代码中,它们在 -0.2 和 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 + ")";
问题出现在第 11 行和第 12 行
从调试中可以看出 x % speed (or 0.25 % 0.05) = 0
!但是 x - x % 速度(或 0.25 - 0)= 0.2
我试过了:
- x -= x % this.speed;
- x = x - x % this.speed;
- x = x - (x % this.speed);
但没有什么能让玩家超过 -0.2 或 0.2。
【问题讨论】:
-
我感觉
speed === 0.05,而不是你说的零 -
打开一个nodejs shell并输入
0.25 % 0.05 -
也许是因为我醒得太久了,但是这段代码是一场噩梦。你能把你的问题缩小到具体问题吗?
-
我知道你的困惑在哪里,哈哈。键入
0.25 / 0.05得到5,但做模数得到0.05的余数。大吃一惊! -
感谢 smac89,我不知道为什么,但是将我的值乘以 100,然后使用模运算符就可以了。我知道由于浮点数学比较值会不准确,但我仍然不明白为什么模数会有问题。它看起来很奇怪
标签: javascript modulus