Sometimes it’s desired to have a distance constraint. That constraint assumes a choosen separation distance for two points fixed in two bodies. I’ve written a derivation for it in 3D and shared here. An implementation should be pretty simple since we have minimally one Jacobian and solve a 1D linear system. Here is an example which you can use in your own projects.

## Appendix

Here’s stuff that worth mentioning.

The boring part of this constraint is that the Jacobian vanishes when this constraint is satisfied. Practically, we solve the problem by skipping the constraint solving when that happens. Another workaround I can recommend is to define 3 distance constraints that keeps two points together and solve them as a 3-by-3 linear system. This is sometimes called a block solver. Separating the points is done by chosing a point outside the volume of the shape of one of the bodies.

Another way to calculate the velocity constraint column vector is to build the gradients of the position constraint with respect to the position vector directly (Jacobian) and multiply it with the velocity vector. I’ll show you below how we get to the result, but it is my advice to not do this unless required.

Remember that if is the position constraint column vector then we can use the chain rule to differentiate it with respect to time to find the velocity constraint column vector:

That is the total derivative of the position constraint. We assume the last term in the right hand side is zero, as usual in game physics.

Of course we can differentiate the velocity constraint to get the acceleration constraint. Again, we can use the chain rule to get

where

Usually it’s not required doing such a workload but I think it is a good vector calculus exercise. The acceleration constraint is not very usefull in game physics because most of the time only position and velocity are stored as state variables (or initial conditions for the ordinary differential equations of motion if you will).

### Example

Let us consider the linear motion of two points and . To keep things down to earth we use block matrices again. Let’s define

That is, the position and the velocity vector, respecively. Then, the vector stacking the 3 distance constraints that keep the points together at anytime is

The Jacobian is then

where is the identity matrix. Note that the Jacobian is a row vector of the gradients. I wrote it here in block form. From those we can identify the velocity constraint vector easely by inspection.

We can see now that building the Jacobian by inspection is more painless, and predict that can be specially in the presence of angular motion.