好的,所以我想制作一个 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 的建议更新了代码。