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.

  • \$\begingroup\$ 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. \$\endgroup\$ Jun 6, 2013 at 1:35

2 Answers 2


No, velocity is independent from elapsed time, so:

if(right key pressed)
    Velocity.X = movementspeed;
    Velocity.X = 0;
Position += Velocity * deltaTime; // elapsed from last frame
  • \$\begingroup\$ 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? \$\endgroup\$ Jun 5, 2013 at 23:11
  • \$\begingroup\$ Yeah, in this situation it's the same. \$\endgroup\$ Jun 5, 2013 at 23:19
  • \$\begingroup\$ 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. \$\endgroup\$ Apr 28, 2018 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.

  if (right key is pressed):
  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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .