JavaScript - 简单的算术错了

时间:2018-04-18 05:51:51

标签: javascript modulus

我试图使用'%'在JavaScript中,但它无法正常工作。我需要了解原因。

这是我的moveTo(x,y)函数。其中x和y是-1,0或1.玩家一次只能在-1和1之间移动到player.speed距离。速度= 0.05并在整个游戏中保持不变。 debug是一个临时的全局变量,用于在出现错误时在屏幕上打印出来。

评论是播放器无法进一步移动时调试屏幕上的内容的结果。玩家应该能够在任何方向移动最远的是-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(或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。

1 个答案:

答案 0 :(得分:0)

剩余(%)是二元运算符。返回除以两个操作数的<p id="item-back-bar-link"> <a id="item-back-bar-link" href="/attendee-home/{{id}}"> // .... </a> </p> 余数。

因此,如果您想使用id运算符,则应将param转换为整数。