Jason,
Rather than having three object attributes,
- Point (x,y) position
- Vector2D (x,y) direction
- Int speed
it is often much easier to combine the direction and speed into a velocity vector. Then you have only two attributes,
- Point (x,y) position
- Vector2D (x,y) velocity
Updating position
When you need to update the object's position, it's as simple as:
position.x += velocity.x * Δt;
position.y += velocity.y * Δt;
where Δt
is your time delta — or time difference — or time step.
Updating position and velocity
It is also very easy this way to handle acceleration (such as from gravity). If you have an acceleration vector, you can update the velocity and position together like this:
position.x += (velocity.x * Δt) + (0.5 * acceleration.x * Δt * Δt);
position.y += (velocity.y * Δt) + (0.5 * acceleration.y * Δt * Δt);
velocity.x += acceleration.x * Δt;
velocity.y += acceleration.y * Δt;
(This is basically the s = vt + ½at² formula from Physics 101.)
Applying a speed
If you want to apply a given speed in some normalized direction, you can set the velocity like this:
velocity.x = normalizedDirection.x * speed;
velocity.y = normalizedDirection.y * speed;
Deriving a speed
And if you need to do the reverse — deriving the speed and direction from a given velocity vector — you can simply use the Pythagorean theorem or the .Length()
method:
speed = velocity.Length();
And once the speed is known, the normalized direction can be calculated by dividing the velocity by the speed (being careful to avoid dividing by zero):
if (speed != 0) {
normalizedDirection.x = velocity.x / speed;
normalizedDirection.y = velocity.y / speed;
} else {
normalizedDirection.x = 0;
normalizedDirection.y = 0;
}