See all glossary terms

Velocity

A velocity is the speed of an entity in a given direction. In physics and in games, we often represent it with a vector:
  • The orientation of the vector is the direction.
  • The length of the vector represents the speed of the entity. The length of a vector is called its magnitude in math.
In GDScript, we can use a Vector2 value to represent a velocity in 2D. For example, the following code represents a velocity of 400 pixels per second to the right:
var velocity := Vector2(400.0, 0.0)
What is the difference between speed and velocity?
Velocity and speed are both terms used to describe how fast an object is moving, but they have slightly different meanings in physics.
  • Speed is a quantity that measures the rate at which an object moves.
  • Velocity is speed and direction. It describes how fast an object moves, but also in what direction it is going.
If a car travels 60 miles per hour, whether it's going down the road or up the road, the speed remains 60 mph. As you can see, speed is always positive. It cannot be negative. Speed does not tell you in which direction the car is moving, only how fast it's moving.
But if we want to describe how fast the car is going and its direction (north, south, up, down...), then that is a velocity.
We can also calculate a velocity vector by multiplying a direction vector and a speed value. This is because multiplying a vector by a number preserves its direction and only changes its length.
For example, the following code calculates a velocity vector of 400 pixels per second to the right. The velocity variable will have the same value as the previous example, Vector2(400.0, 0.0):
var direction := Vector2(1.0, 0.0)
var speed := 400.0
var velocity := direction * speed
Often, in gameplay code, we separate the direction and speed values. We make the speed editable and calculate the direction based on the player's input or the game's logic. A basic example of this is the following player movement code:
var speed := 400.0

func _process(delta: float) -> void:
	var direction := Input.get_vector("move_left", "move_right", "move_up", "move_down")
	var velocity := direction * speed
	position += velocity * delta

See Also

Related terms in the Glossary