gpt4 book ai didi

c# - Monogame 向方向移动

转载 作者:太空宇宙 更新时间:2023-11-03 21:35:46 25 4
gpt4 key购买 nike

我正在创建一个基于小行星的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com