Shame on me, but I miss to understand the geometry (and/or algebra) which justifies the line of code float mX = (-x1+x)*ca + (-y1+y)*sa;.
How is it that that works fine?
Thanks

/**
* 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;
}

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).

again (-x1+x)*ca + (-y1+y)*sa is the dot product explained above. Say the dot product is a, then x = x1 + a * ca is basically moving from the point (x, y) along the line… but I guess you should look for some material instead of someone explaining this here… I studied math in Japan so I don’t know any good material in English but if anyone suggestions that would be great.