# forward motion car physics - gradual slow

Im having trouble creating realistic car movements in xna 4. Right now i have a car going forward and hitting a terminal velocity which is fine but when i release the up key i need to the car to slow down gradually and then come to a stop. Im pretty sure this is easy code but i cant seem to get it to work

the code - update

``````if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
double elapsedTime = gameTime.ElapsedGameTime.Milliseconds;
CalcTotalForce();
Acceleration = Vector2.Divide(CalcTotalForce(), MASS);
Velocity = Vector2.Add(Velocity, Vector2.Multiply(Acceleration, (float)(elapsedTime)));
Position = Vector2.Add(Position, Vector2.Multiply(Velocity, (float)(elapsedTime)));
}
``````

added functions

``````public Vector2 CalcTraction()
{
//Traction force = vector direction * engine force
return Vector2.Multiply(forwardDirection, ENGINE_FORCE);
}
public Vector2 CalcDrag()
{
//Drag force = constdrag * velocity * speed
return Vector2.Multiply(Vector2.Multiply(Velocity, DRAG_CONST), Velocity.Y);
}

public Vector2 CalcRoll()
{
//roll force = const roll * velocity
return Vector2.Multiply(Velocity, ROLL_CONST);
}

public Vector2 CalcTotalForce()
{
//total force = traction + (-drag) + (-rolling)
return Vector2.Add(CalcTraction(),
Vector2.Add(-CalcDrag(), -CalcRoll()));
}
``````

anyone have any ideas?

-
you answered your own question about how to fix your own code. – GameDev-er Jan 11 '13 at 22:50

## 1 Answer

The answer was simple:

Take Position out of the keyboard method and have it at the end of the update function. then add to "on key up" call a deceleration vector. i.e

`````` if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
Acceleration = Vector2.Divide(CalcTotalForce(), MASS);
Velocity = Vector2.Add(Velocity, Vector2.Multiply(Acceleration, (float)(elapsedTime)));
}
else if(Keyboard.GetState().IsKeyUp(Keys.Up))
{
if (Velocity.Y < 0)
Velocity = Vector2.Add(Velocity, Vector2.Multiply(decceleration, (float)(elapsedTime)));
}
``````
-