【问题标题】:C# XNA determine if Vector2 is facing another Vector2C# XNA 确定 Vector2 是否面向另一个 Vector2
【发布时间】:2015-10-10 19:34:27
【问题描述】:

我正在开发一款 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);
}

【问题讨论】:

    标签: c# vector xna


    【解决方案1】:

    哎呀,在尝试了一些东西之后我想通了。

    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);
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多