# Physics-Based Velocity Tracker

If you want a game character or game object to follow a desired velocity, you can usually just set the desired velocity in a game engine. However, if you are dealing with physical disturbances — such as being hit by flying soccer balls or running into a wall — then you’ll no longer be moving at the desired velocity.

Physics disturbances can change not only the speed of motion, but also the direction that you’re moving in. To return to the desired velocity, you can use a second order spring simulation. Assuming that there is no desired position, then you can conclude that the game object is always in the correct position — just that it does not always have the correct velocity.

### Math Background

A second order spring simulation uses the following mathematical expression:

F = k * x + d * v

Where F is the force, k is the spring stiffness constant, x is the distance from the desired position, d is the spring damping constant, and v is the difference between the current velocity and the desired velocity. As you recall, we have no desired position which means that we are always in the correct position. Therefore, x is always equal to 0, and the expression simplifies to the following:

F = d * v

### Code Implementation

The following function computes the required force to apply to the game object, such that it will always attempt to move towards the desired velocity. Note that if it is already moving at the desired velocity, then the computed force will be zero.

`Vector3 getVelocityTrackerForce() {    Vector3 v_ij = desVel — currVel;    Vector3 springForce = D * v_ij;    return springForce;}`

If you want to apply this force to the game object, then there are a variety of ways to do so. You can either call an applyForce() function, or you can calculate the acceleration via F = ma and then add the computed acceleration to the game object’s current acceleration.

### Applications

This velocity tracker is especially useful for non-player characters (NPC’s) that are controlled by artificial intelligence. If the playable character bumps into an NPC, then the NPC will want to return to its desired velocity after its been physically disturbed. The NPC might not have had a particular position in mind, but it probably had a desired speed and direction it wanted to follow as it walked down the street.

This also applies to a playable character. The playable character might only have a direction and speed in mind. So if he bumps into something or someone, he will adjust and correct to his desired velocity and direction.

That’s it!