gpt4 book ai didi

c# - 如何找到线上最近的点?

转载 作者:行者123 更新时间:2023-11-30 13:43:42 24 4
gpt4 key购买 nike

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

最佳答案

无限长度:

如果你有一条无限长的线,起点方向,计算线方向的点积,然后乘以方向并加上起点.

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

关于c# - 如何找到线上最近的点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com