Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
    
you answered your own question about how to fix your own code. –  GameDev-er Jan 11 '13 at 22:50
add comment

1 Answer 1

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)));
            }
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.