We know the points P1, P2, and P3, and we need to calculate the closest point from P3 to P1->P2. In the above picture, the closest point is the point P2. The calculation steps are as follows:
1. First, we calculate the orthogonal projection point C on the line segment from P3 to P1->P2
2. According to the ratio of P1->C to the length of P1->P2, the ratio is obtained
3. Limit the ratio to the interval [0,1]
4. After obtaining the ratio, it is consistent with the calculation of any point between the two points in the previous article. The starting point vector P1 plus P1->P2 multiplied by the ratio gets the closest point from P3 to P1->P2
The calculation code is as follows:
public Vector2 GetClosestPoint(Vector2 p1, Vector2 p2, Vector2 p3)
{
Vector2 from_p1_to_p3 = p3 - p1;
Vector2 from_p1_to_p2 = p2 - p1;
//计算投影点
float dot = Vector2.Dot(from_p1_to_p3, from_p1_to_p2.normalized);
dot /= from_p1_to_p2.magnitude;
float t = Mathf.Clamp01(dot);
return p1 + from_p1_to_p2 * t;
}
Here we mainly explain why the projection point is calculated in this way. First, according to the point multiplication formula:
Here, P1 to P2 are taken as standard vectors, and its length is 1, so the calculated dot is actually the length of P1->P3 multiplied by the cosine of the angle of P1, that is, the length of P1->C. The length calculated here is the projection length
Then restricting the points to between P1 and P2 is the closest point we are looking for.