reposting the snippet as a reference:

```
/**
* Returns a point on the line (x1,y1) -> (x2,y2)
* that is closest to the point (x,y)
*
* The result is a PVector.
* result.x and result.y are points on the line.
* The result.z variable contains the distance from (x,y) to the line,
* just in case you need it :)
*/
PVector getDistance( float x1, float y1, float x2, float y2, float x, float y ){
PVector result = new PVector();
float dx = x2 - x1;
float dy = y2 - y1;
float d = sqrt( dx*dx + dy*dy );
float ca = dx/d; // cosine
float sa = dy/d; // sine
float mX = (-x1+x)*ca + (-y1+y)*sa;
if( mX <= 0 ){
result.x = x1;
result.y = y1;
}
else if( mX >= d ){
result.x = x2;
result.y = y2;
}
else{
result.x = x1 + mX*ca;
result.y = y1 + mX*sa;
}
dx = x - result.x;
dy = y - result.y;
result.z = sqrt( dx*dx + dy*dy );
return result;
}
```

let’s say we use the figure from wikipedia

this code (I flipped inside the parenthesis)

```
float mX = (x-x1)*ca + (y-y1)*sa;
```

is a dot product of `(x-x1, y-y1)`

and `(ca, sa)`

. The former is a vector from `(x1, y1)`

to `(x, y)`

, corresponding to **a** in the figure. The latter is a vector from `(x1, y1)`

to `(x2, y2)`

but normalized (as divided by `d`

): **b** in the figure. The dot product can be thought as a projection, and since `(ca, sa)`

is normalized and is a unit vector, the result `mX`

is the length of `(x-x1, y-y1)`

or **a** projected on **b** (in the figure, `mX`

corresponds to the length of **a1**).