c# - Monogame 向方向移动

标签 c# monogame

我正在创建一个基于小行星的 2D 游戏。在那场比赛中,我需要将船推向一个方向。

我可以画出这艘船,让它掉头。但是当谈到推进它时,我的问题出现了。

我似乎无法理解这个问题。 (整个制作游戏的过程对我来说都是新鲜事物 ^^)

播放器.cs

protected Vector2 sVelocity;
protected Vector2 sPosition = Vector2.Zero;
protected float sRotation;
private int speed;

public Player(Vector2 sPosition)
        : base(sPosition)
{
    speed = 100;
}

public override void Update(GameTime gameTime)
{
    attackCooldown += (float)gameTime.ElapsedGameTime.TotalSeconds;

    // Reset the velocity to zero after each update to prevent unwanted behavior
    sVelocity = Vector2.Zero;

    // Handle user input
    HandleInput(Keyboard.GetState(), gameTime);

    if (sPosition.X <= 0)
    {
        sPosition.X = 10;
    }

    if (sPosition.X >= Screen.Instance.Width)
    {
        sPosition.X = 10;
    }

    if(sPosition.Y <= 0)
    {
        sPosition.Y = 10;
    }

    if (sPosition.Y >= Screen.Instance.Height)
    {
        sPosition.Y = 10;
    }

    // Applies our speed to velocity
    sVelocity *= speed;

    // Seconds passed since iteration of update
    float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

    // Multiplies our movement framerate independent by multiplying with deltaTime
    sPosition += (sVelocity * deltaTime);

    base.Update(gameTime);
}

private void HandleInput(KeyboardState KeyState, GameTime gameTime)
{
    if (KeyState.IsKeyDown(Keys.W))
    {
        //Speed up
        speed += 10;
        sVelocity.X = sRotation; // I know this is wrong
        sVelocity.Y = sRotation; // I know this is wrong
    }
    else
    {
        //Speed down
        speed += speed / 2;
    }

    if (KeyState.IsKeyDown(Keys.A))
    {
        //Turn left
        sRotation -= 0.2F;
        if (sRotation < 0)
        {
            sRotation = sRotation + 360;
        }
    }
    if (KeyState.IsKeyDown(Keys.D))
    {
        //Turn right
        sRotation += 0.2F;
        if (sRotation > 360)
        {
            sRotation = sRotation - 360;
        }
    }
}

我离正确还是很远?

最佳答案

sRotation 是一个角度,sVelocity 是一个速度。你需要三角函数。

例如,您可以使用类似的东西(我没有测试符号的正确性):

 if (KeyState.IsKeyDown(Keys.W))
    {
        //Speed up
        speed += 10;
        sVelocity.X = Math.cos(sRotation * 2 * Math.PI / 360);
        sVelocity.Y = -Math.sin(sRotation * 2 * Math.PI / 360);
    }

这会解决您的问题吗?

编辑:您的“减速”公式是错误的。你目前正在添加 speed/2speed,你应该有一些东西:

speed = speed / 2; // note the "=", not "+="

此外,使用类似的东西可能更可取:

if (speed > 0) { 
    speed -= 5;
} else {
    speed = 0;
}

关于c# - Monogame 向方向移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21990294/

相关文章:

c# WCF 捕获基本类型的错误异常

transparency - 在 MonoGame 运行时更改纹理透明度

c# - 如何在单游戏中使用或制作 "Effects"?

c# - Monogame XAML 重置 CoreWindow?

c# - 如何从 Windows 8.1 中的导航堆栈中删除后退条目?

具有固定数组大小的 C# ToArray()

c# - 无法以编程方式设置 WPF 的 ComboBox 项文本

macos - Mac 上的 Monogame 管道错误 : System. DllNotFoundException : libfreeimage. dylib

c# - 如何避免人们使用我在文本框中支持的字符以外的其他字符?

c# - 我的 Web API 服务需要访问 token 吗?