I'm working on a school project, in which I'm making an astroids clone. I've been working on player movement and have implemented the code below.
I'm getting some weird behavior when trying to move the player sprite backward and I'm having a hard time understanding the math behind it.
I've commented below where the problem is
position = velocity position;
if (Keyboard.GetState().IsKeyDown(Keys.Left)) rotation -= 0.1f;
if (Keyboard.GetState().IsKeyDown(Keys.Right)) rotation = 0.1f;
if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
velocity.X = (float)Math.Cos(rotation) * tangentialVelocity;
velocity.Y = (float)Math.Sin(rotation) * tangentialVelocity;
}
//this is where I need help
if (Keyboard.GetState().IsKeyDown(Keys.Down))
{
velocity.X = (float)Math.Cos(rotation) - tangentialVelocity;
velocity.Y = (float)Math.Sin(rotation) - tangentialVelocity;
}
else if (velocity != Vector2.Zero)
{
float i = velocity.X;
float j = velocity.Y;
velocity.X = i -= friction * i;
velocity.Y = j -= friction * j;
}
CodePudding user response:
It seems to me like the logic for forwards/backwards thrust should be as follows:
Given some variable like int thrustPower = 1.0f;
if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
velocity.X = (float)Math.Cos(rotation) * thrustPower;
velocity.Y = (float)Math.Sin(rotation) * thrustPower;
}
if (Keyboard.GetState().IsKeyDown(Keys.Down))
{
velocity.X -= (float)Math.Cos(rotation) * thrustPower;
velocity.Y -= (float)Math.Sin(rotation) * thrustPower;
}
So that if either Keys.Up
or Keys.Down
is pressed, the velocity on each axis will scale by the normal amount of ThrustPower
projected onto that axis.
This also gets around the problem of having to deal with what you call tangentialVelocity
, but I assume should actually be radialVelocity
or just speed
.