【问题标题】:Enemy sprite takes a strange path towards the player敌人精灵向玩家走去一条奇怪的路径
【发布时间】:2013-03-13 10:21:07
【问题描述】:

我试图让我的画布游戏中的精灵不断向玩家移动,直到它发生碰撞。执行此操作的相关函数是 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

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

我为使敌人向玩家移动而进行的计算有什么问题?

【问题讨论】:

    标签: javascript math canvas 2d-games


    【解决方案1】:

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

    而不是 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。

    【讨论】:

    • -2.35 在那里是因为精灵从错误的旋转开始,这只是现在的快速修复,但它是正确的 :) 此外,修复工作。谢谢!我现在发现我一直在使用错误的方法让精灵跟随玩家,因为它们会绕着玩家转圈而不是直接朝他们移动。
    • @JamesDawson,通过交换 cos 和 sin,基本上你所做的就是让怪物瞄准相对于“他们想去的地方”成 90 度角。所以他们会绕圈移动也就不足为奇了。
    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2021-04-11
    • 1970-01-01
    相关资源
    最近更新 更多