3

好的,所以我想制作一个 javascript/html 画布游戏,其中玩家被一些敌人跟踪,经过一点“研究”,她是我的怪物(敌人)类中最重要的部分:

  this.UpdateAngle = function() {
    this.dx = this.x - player.x;
    this.dy = this.y - player.y;
    this.angle = Math.atan2(this.dy, this.dx) * 180 / Math.PI;
    if (this.angle < 0) {
      this.angle += 2 * Math.PI;
    }
  }
  this.UpdateSpeed = function() {
    this.speedX = this.speed * Math.cos(this.angle);
    this.speedY = this.speed * Math.sin(this.angle);
  }
  this.Move = function() {
    this.UpdateAngle();
    this.UpdateSpeed();
    this.x += this.speedX;
    this.y += this.speedY;
  }

所以我在这里的意思是计算从敌人到玩家的角度,然后使用andatan2()计算我应该在 x 和 y 轴上移动多少,我计算的速度和角度,然后只是移动计算的像素。cos()sin()

这一切似乎运作良好,直到我移动玩家,然后敌人开始向奇怪的方向移动。我不知道出了什么问题,如果有人能告诉我这是怎么做的,那就太棒了。:D

您可以在这里看到它的实际效果。*我已根据 PremierBromanov 的建议更新了代码。

4

2 回答 2

2

它可能与这个块有关

this.angle = Math.atan2(this.dy,this.dx) * 180 / Math.PI;
    if (this.angle < 0) {
      this.angle += 2 * Math.PI;

您正在使用Math.atan2which 以弧度为单位输出角度,然后您将转换为度数* 180 / Math.PI;之后,您将检查它是否小于零并将 2Pi 添加到角度以确保它正确计算它的实际角度一个完整的圆减去角度。但是,您在这里使用的是弧度而不是度数。因此,当您的代码为负数时,您将 2Pi 添加到度数上,这不是很多,但有时会导致它变为正数。这就是为什么当你移动时你的点在旋转。如果你注意到,当你离得更远时,这些点旋转得更慢,这意味着负角大于 2Pi,因此不会立即转圈。

简而言之,尝试将其更改为

if (this.angle < 0) {
      this.angle += 360;
    }
于 2014-12-17T19:52:11.897 回答
1

好的,所以实际上是布罗马诺夫总理回答了这个问题,谢谢,但我不能接受评论,因为它是,所以我会这样做以使其更清楚,如果有人也应该过来并想要答案。我做的数学有点错误,这就是我的代码最终的样子:

this.UpdateAngle = function() {
  this.dx = player.x - this.x;
  this.dy = player.y - this.y;
  this.distance = Math.sqrt((this.dx*this.dx) + (this.dy*this.dy));
  this.angle = Math.atan2(this.dy,this.dx) * 180 / Math.PI;
}
  this.UpdateSpeed = function() {
  this.speedX = this.speed * (this.dx/this.distance);
  this.speedY = this.speed * (this.dy/this.distance);
}
this.Move = function() {
  this.UpdateAngle();
  this.UpdateSpeed();
  this.x += this.speedX;
  this.y += this.speedY;
}

再次感谢布罗马诺夫总理,这是他的回答,也感谢其他所有人,这是我的第一篇文章,我很高兴我得到了这么快的回复!(我是这里最慢的):D

于 2014-12-23T00:33:40.730 回答