如何规范 Monogame 中的对角线移动

abl*_*ozy 1 c# monogame

我有一些简单的运动代码,唯一的问题是对角线运动比 X 和 Y 运动更快。我知道如何在 Unity 中标准化这一点,但不知道如何在 Monogame 中标准化。

private Vector2 _position;

protected override void Update(GameTime gameTime)
{
     

    if (Keyboard.GetState().IsKeyDown(Keys.W))
    {
        _position.Y -= 1;
    }

    if (Keyboard.GetState().IsKeyDown(Keys.S))
    {
        _position.Y += 1;
    }

    if (Keyboard.GetState().IsKeyDown(Keys.A))
    {
        _position.X -= 1;
    }

    if (Keyboard.GetState().IsKeyDown(Keys.D))
    {
        _position.X += 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该是所有相关代码,如果您需要更多,请告诉我。

Jon*_*asH 5

你可能应该这样做:

var dir = Vector2.Zero;
if (Keyboard.GetState().IsKeyDown(Keys.W))
{
    dir .Y -= 1;
}
// Same for all keys
....

// skip further processing if no keys are pressed.
if(dir == Vector.Zero)
    return;

// Ensure the vector has unit length
dir.Normalize(); 
// Define a speed variable for how many units to move
// Should probably also scale the speed with the delta time 
var deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
_position += dir * speed * deltaTime; 
Run Code Online (Sandbox Code Playgroud)

我对单游戏不太熟悉。但总体方法应该是计算移动方向,对其进行标准化,并将其缩放到适当的速度,这在任何类型的游戏中都应该有效。