C#XNA确定Vector2是否面向另一个Vector2

时间:2015-10-10 19:34:28

标签: c# vector xna

我正在开发2D游戏。我试图弄清楚如何确定一个Vector2是否面向另一个。

这是我到目前为止所做的:

public void update(GameTime gameTime, Vector2 playerPosition)
{
    // position is "enemy" Vector2
    // rotationAngle is the angle which the "enemy" is facing
    // I need to determine if the "enemy" should rotate left, right, or move forward
    // The goal is to have the "enemy" move towards the player
    float angle = MathHelper.ToDegrees((float)Math.Atan2(playerPosition.Y - position.Y, playerPosition.X - position.X));
    float rotationDegrees = MathHelper.ToDegrees(rotationAngle);
    // Now what????





    update(gameTime);
}

1 个答案:

答案 0 :(得分:1)

Gah,在尝试了一些东西后,我想出来了。

public void update(GameTime gameTime, Vector2 playerPosition)
{
    float angle = MathHelper.ToDegrees((float)Math.Atan2(playerPosition.Y - position.Y, playerPosition.X - position.X));
    float rotationDegrees = MathHelper.ToDegrees(rotationAngle);
    var diff = ((rotationDegrees - angle) + 360) % 360;
    if (diff > 90)
    {
        // bool for rotate method determines if rotating left or right
        rotate(false);
    }
    else
    {
        rotate(true);
    }

    if (diff < 180 && diff > 0)
    {
        moveForward();
    }

    update(gameTime);
}

编辑:我的计算存在一些问题。在某些情况下,敌人会被卡住。问题在于,每次游戏更新时,有时价值会从负值变为正值。解决方案是确保差异始终为正。