XNA Using velocity

Previously when making games I have just been using a Vector2 as the sprites position and altering that for movement, i.e.:

if(right key pressed)
Position.X += movementspeed * gametime...;


However I now have the need to use a velocity vector for movement. So far what i'm doing is:

if(right key pressed)
Velocity.X = movementspeed * gametime...;
...
Position += Velocity;
Velocity = Vector2.Zero; // Set velocity to 0


Is this how Velocity is implemented? I.e. setting it to a zero vector after each call of update?

Many thanks

Edit: When I stop pressing the key the sprite must stop moving, hence setting the velocity to zero.

• If it's only moving when the button is pressed, it's not really velocity. It's just a one-time position change. Having the Velocity variable in your code does nothing, especially because you set it back to zero each frame. You might just as well add directly to the Position property. – Seth Battin Jun 6 '13 at 1:35

No, velocity is independent from elapsed time, so:

if(right key pressed)
Velocity.X = movementspeed;
else
Velocity.X = 0;
...
Position += Velocity * deltaTime; // elapsed from last frame

• Ok that's brilliant thanks for the help! Out of interest would me setting the velocity vector to zero accomplish what the else statements would? – Lee Brindley Jun 5 '13 at 23:11
• Yeah, in this situation it's the same. – Mephistofeles Jun 5 '13 at 23:19
• Be careful setting the Vector2 to Zero though if you want to maintain your Velocity on the Y axis. This is old but I came across this so I imagine others will. – cossacksman Apr 28 '18 at 13:11

So first off: I don't know what kind of game you're making. If it's a top-down RPG, or anything where movement isn't really central to the mechanics, this approach is fine. If it's a Mario-like platformer, you may want to take the indirection one step further.

Try playing a Mario clone somewhere, and you'll notice he works up to full speed, and then takes a few frames to slow down when you let go of Right. This is accomplished through acceleration. Here's the pseudocode.

Update():
if (right key is pressed):
Acceleration = ACCELERATION_CONSTANT
else if (Velocity != 0):
// apply a braking force that will bring him back to 0. This should be in the
// opposite direction he's travelling, but not dependent on the speed he's travelling.
Acceleration = SMALL_BRAKING_CONSTANT * Vector2.Unit(-Velocity)
Velocity += Acceleration * time
Velocity = min(Velocity, VelocityMax) // prevent Mario from going too fast
// at some point, you might have other influencers on the velocity, like collision
//detection. In basic games that's often done just by directly correcting position.
Position += Velocity
Velocity = 0