5

我有一个点(A)和一个向量(V)(假设它是无限长的),我想找到离我的原点(A)最近的点(B)。使用 Unity Vector2 或 Vector3 的最简单表达式是什么?

4

3 回答 3

21

无限长

如果你有无限长度的线startdirection,计算线方向的点积,然后将它乘以方向并将起点添加到它。

public Vector2 FindNearestPointOnLine(Vector2 origin, Vector2 direction, Vector2 point)
{
    direction.Normalize();
    Vector2 lhs = point - origin;

    float dotP = Vector2.Dot(lhs, direction);
    return origin + direction * dotP;
}

有限长度

如果您的线具有有限长度且具有开始结束的位置,请获取标题以执行从起点到终点的投影。另外,用Mathf.Clamp它来拍手,以防线路断开。

public Vector2 FindNearestPointOnLine(Vector2 origin, Vector2 end, Vector2 point)
{
    //Get heading
    Vector2 heading = (end - origin);
    float magnitudeMax = heading.magnitude;
    heading.Normalize();

    //Do projection from the point but clamp it
    Vector2 lhs = point - origin;
    float dotP = Vector2.Dot(lhs, heading);
    dotP = Mathf.Clamp(dotP, 0f, magnitudeMax);
    return origin + heading * dotP;
}
于 2018-08-18T06:55:48.947 回答
3
// For finite lines:
Vector3 GetClosestPointOnFiniteLine(Vector3 point, Vector3 line_start, Vector3 line_end)
{
    Vector3 line_direction = line_end - line_start;
    float line_length = line_direction.magnitude;
    line_direction.Normalize();
    float project_length = Mathf.Clamp(Vector3.Dot(point - line_start, line_direction), 0f, line_length);
    return line_start + line_direction * project_length;
}

// For infinite lines:
Vector3 GetClosestPointOnInfiniteLine(Vector3 point, Vector3 line_start, Vector3 line_end)
{
    return line_start + Vector3.Project(point - line_start, line_end - line_start);
}
于 2020-07-13T09:16:19.123 回答
2

对于无限线:

Vector3 GetPoint(Vector3 p, Vector3 a, Vector3 b)
{
    return a + Vector3.Project(p - a, b - a);
}

此方法适用于Vector3输入,并且如果参数Vector2自动转换为Vector2. Vector2如果需要,输出将隐式转换为 a 。

于 2019-03-12T02:25:18.887 回答