【发布时间】:2023-05-27 05:07:01
【问题描述】:
我正在创建一个基于小行星的 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;
}
}
}
我离权利很近,还是离权利很远?
【问题讨论】:
-
你在每一帧中都使用
sVelocity *= speed:如果speed是10并且sVelocity是(0,1)你会非常很快地移动到@987654327 @(即:在 3 帧中,您将以每帧 100 万个单位移动)。我怀疑这条线是你意外移动的最大罪魁祸首...... -
@DanPuzey 他每帧都有
sVelocity = Vector.Zero。失控的可能是speed值本身。 -
@dureuill:啊,我错过了那个重置。您可能是对的 - 控制过快的速度将有助于了解旋转情况。