javascript - 敌人 Sprite 以奇怪的方式走向玩家

标签 javascript math canvas 2d-games

我试图让我的 Canvas 游戏中的 Sprite 不断向玩家移动,直到它发生碰撞。执行此操作的相关函数是 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.x, this.y, this.rotation and this.speed 为X位置, 分别是敌人的 Y 位置、旋转和速度。

这有点管用,但是敌人离玩家大约 300 像素,然后开始向左偏转并远离玩家,与它朝玩家的方向成 90 度 Angular 。

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

敌人是橙色 Sprite ,玩家是白色 Sprite 。

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

最佳答案

从之前写的angle/movement代码来看,这些可能是错误的:

代替 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;

推理:如果您的 Angular 为 0 = 东(并且如果您使用数学库函数,它们默认为东),那么对于 Angular 0,您需要最大的水平移动而没有垂直移动 - cos(0) = 1 和 sin (0) = 0。

关于javascript - 敌人 Sprite 以奇怪的方式走向玩家,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15375878/

相关文章:

javascript - 如何阻止 Javascript 重复执行该函数?

Javascript:从 Font Awesome 获取符号 unicode

java - 数学乒乓球游戏

java - 将角度保持在 -179 到 180 度之间的简单方法

javascript - 对象没有方法 'setupState'

javascript - 在导出的组件中使用 “ElementRef” 时出错

javascript/jquery 循环函数

python - 牛顿法在浮点运算中的不同实现

android - 旋转位图(比 Canvas 大)但以 Canvas 为中心

javascript - 适用于 Android 28 的 Chrome : HTML Canvas RadialGradient renders incorrectly