代码之家  ›  专栏  ›  技术社区  ›  James Dawson

敌方精灵朝玩家走了一条奇怪的路

  •  1
  • James Dawson  · 技术社区  · 12 年前

    我试图让画布游戏中的精灵不断向玩家移动,直到它碰撞。执行此操作的相关功能是 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 this.speed 分别是敌人的X位置、Y位置、旋转和速度。

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

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

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

    我为了让敌人向玩家靠近而进行的计算有什么问题?

    1 回复  |  直到 12 年前
        1
  •  2
  •   Patashu    12 年前

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

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