敌人精灵朝着玩家走了一条奇怪的道路

Enemy sprite takes a strange path towards the player

本文关键字:道路 一条 走了 精灵 玩家 敌人      更新时间:2023-09-26

我试图让我的画布游戏中的精灵不断向玩家移动,直到它发生碰撞。相关的函数是update()函数:

Enemy.prototype.update = function(playerX, playerY) {
    // Rotate the enemy to face the player
    this.rotation = Math.atan2(this.y - playerY, this.x - playerX) - 2.35;
    // Move in the direction we're facing
    this.x += Math.sin(this.rotation) * this.speed;
    this.y += Math.cos(this.rotation) * this.speed;
}

this.xthis.ythis.rotationthis.speed分别为敌人的X位置、Y位置、旋转和速度。

这是可行的,但是敌人离玩家大约300像素,然后开始转向左边并远离玩家,与它朝向玩家的方向成90度角。

由于这有点难以解释,我录制了一个快速视频来帮助展示问题:http://www.screenr.com/AGz7

敌人是橙色精灵,玩家是白色精灵。

我所做的让敌人向玩家移动的计算有什么问题?

从之前编写的角度/移动代码来看,这些可能是错误的:

代替this.rotation = Math.atan2(this.y - playerY, this.x - playerX) - 2.35;

this.rotation = Math.atan2(playerY - this.y, playerX - this.x);

给你正确的旋转?

推理:不要使用神奇的常数,试着找出为什么你的公式是错误的。

不是

this.x += Math.sin(this.rotation) * this.speed;
this.y += Math.cos(this.rotation) * this.speed;

this.x += Math.cos(this.rotation) * this.speed;
this.y += Math.sin(this.rotation) * this.speed;

推理:如果你的角度是0 =基于东的(如果你使用数学库函数,它们是默认的),那么对于一个角度0,你想要最大的水平移动而不是垂直移动- cos(0) = 1和sin(0) = 0。