[Math] Distance from a point to a line in 2D.

I have 3 points for example:

Vector2 M = new Vector2(1, 2);
Vector2 B = new Vector2(5, 6);
Vector2 C = new Vector2(3, 4);
//BC - vector:
Vector2 BC  = B - C;

I want to compute the distance from M to BC. I came up with two methods that I think are too expensive:

float slopeBC = BC.y / BC.x;
float distance = Mathf.abs(slopeBC * M.x - M.y + slopeBC * B.x + B.y)/Mathf.sqrt(1 + slopeBC * slopeBC);

or

Vector3 MB = M - B;
Vector3 MC = M - C;
float p = (MB.magnitude + MC.magnitude + BC.magnitude)/2
float distance = 2 * Mathf.sqrt(p*(p - MB.magnitude)*(p - MC.magnitude)*(p - BC.magnitude)) / BC.magnitude;

They seem to work, but they also seem to use heavy-weight calculations.

Check out this thread of mine for the most optimal 2D intersector I’ve come across. Read through it and there are also nearest point implementations for lines, rays, and segments.

1 Like