I am trying to implement acceleration and drag into my top-down 2D game. The player can move using the WASD keys. Acceleration works fine, but the way I handle the directional velocity causes the player to abruptly stop when the movement keys are released instead of coming to a stop. Here is the code I currently have:
EDIT: I officially solved the above issue by implementing an applyForce method and triggering it when the movement keys are pressed as seen here:
public void applyForce(float angle, float amount)
{
Vector2 v = new Vector2((float)(Math.Cos(angle)), (float)(Math.Sin(angle)));
v.Normalize();
v = Vector2.Multiply(v, amount);
velocity = Vector2.Add(velocity, v);
}
if (oldKeys.IsKeyDown(Keys.A))
{
applyForce((float)Math.PI, CurrentSpeed);
}
if (oldKeys.IsKeyDown(Keys.D))
{
applyForce(0, CurrentSpeed);
}
if (oldKeys.IsKeyDown(Keys.W))
{
applyForce((float)Math.PI * 1.5f, CurrentSpeed);
}
if (oldKeys.IsKeyDown(Keys.S))
{
applyForce((float)Math.PI * 0.5f, CurrentSpeed);
}
As you may have guessed, the new problem is that when 2 keys are pressed the method is called twice causing the player to move faster than he should be. Are there any effective ways of handling this?