# How to make a smooth movement in XNA?

I'm trying to make a nice controls for my game, but I can't achieve enough SMOOTHNESS.

if (kbState.GetPressedKeys().Length != 0 && _direction != Vector2.Zero)
{
_direction.Normalize();
_position += _direction * (_speed * (float)gameTime.ElapsedGameTime.TotalSeconds);
}
else
_direction = Vector2.Zero;

if (kbState.IsKeyDown(Keys.W))
{
_direction += new Vector2(0, -1f);
}
if (kbState.IsKeyDown(Keys.S))
{
_direction += new Vector2(0, 1);
}

if (kbState.IsKeyDown(Keys.D))
{
_direction += new Vector2(1, 0);
}

if (kbState.IsKeyDown(Keys.A))
{
_direction += new Vector2(-1, 0);
}


There is the code. Could you help me a little and give an advice how to make character stop smoothly. I tried many options, but could'nt find any that fit.

• Move less each frame? – Doorknob Jan 21 '13 at 0:03
• Does this help? stackoverflow.com/questions/6841575/… – user24821 Jan 21 '13 at 0:32
• You want it to stop smoothly? like some sort of pseudo-friction? – Luis Estrada Jan 21 '13 at 1:39
• Luis, exactly, pseudo-friction! – edwing Jan 21 '13 at 12:12

Here is how I usually simulate friction:

    Vector2 Velocity;
float Friction; // In pixels / second^2

void ApplyFriction() {
if (Velocity.X > 0) Velocity.X -= Friction;
if (Velocity.X < 0) Velocity.X = 0;
}


You then put the function at the end of your character's presumed Update() method.

If you want constant movement, you can set Friction to 0 until you want it enabled again (as in, when you want your character to stop). (y)

PROTIP: You can transform this in a Gravity function by turning the code into Velocity.Y += GravitySpeed; if (Velocity.Y > TerminalVelocity) Velocity.Y = TerminalVelocity!

You need velocity Assuming fixed time step:

if(noKeysPressed)
{