直線距離に1ポイント
リンク:https://www.jianshu.com/p/8ba826e6208a
private static float distancePoint2Line(Vector3 point, Vector3 linePoint1, Vector3 linePoint2)
{
float cos = Vector3.Dot(point - linePoint1, (linePoint1 - linePoint2).normalized);
return Mathf.Sqrt((point - linePoint1).sqrMagnitude - cos * cos);
}
直線距離に2ポイント
/// <summary>
/// 点到线段的距离
/// </summary>
/// <param name="point">点</param>
/// <param name="start">起点</param>
/// <param name="end">终点</param>
/// <returns>距离,如果不在线段范围内,返回-1 </returns>
public static float DistancePoint2Segment(Vector3 point, Vector3 start, Vector3 end)
{
Vector3 line = end - start;
//获取点point在直线line上的投影位置
Vector3 projectPoint = start + Vector3.Project(point - start, line);
//计算投影点是否在线段外
//如果与line方向不一致,表示在线段外部
if (Vector3.Dot((projectPoint - start).normalized, line.normalized) < 0) return float.MaxValue;
//如果长度超过线段的长度,表示在选定外部
if (Vector3.Distance(start, end) < Vector3.Distance(projectPoint, start)) return float.MaxValue;
return Vector3.Distance(projectPoint, point);
}
3.線分が交差
リンク:失われた(上の補足あります)
/// <summary>
/// 两线是否相交
/// </summary>
/// <param name="s1">线段1 起点</param>
/// <param name="e1">线段1 终点</param>
/// <param name="s2">线段2 起点</param>
/// <param name="e2">线段2 终点</param>
/// <returns></returns>
public static bool IsIntersect(Vector3 s1, Vector3 e1, Vector3 s2, Vector3 e2)
{
//排斥
if (Mathf.Max(s1.x, e1.x) < Mathf.Min(s2.x, e2.x))
return false;
if (Mathf.Min(s1.x, e1.x) > Mathf.Max(s2.x, e2.x))
return false;
if (Mathf.Max(s1.y, e1.y) < Mathf.Min(s2.y, e2.y))
return false;
if (Mathf.Min(s1.y, e2.z) > Mathf.Max(s2.y, e2.y))
return false;
//跨立
float c1 = Corss(s1, e1, s2);
float c2 = Corss(s1, e2, e1);
float c3 = Corss(s2, e2, s1);
float c4 = Corss(s2, e1, e2);
if (c1 * c2 > 0 && c3 * c4 > 0)
return true;
return false;
}
/// <summary>
/// 差积
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="q1"></param>
/// <returns></returns>
private static float Corss(Vector3 p1, Vector3 p2, Vector3 q1)
{
//将点在一个平面内
p1.y = p2.y = q1.y = 0;
Vector3 v1 = p2 - p1;
Vector3 v2 = q1 - p1;
float corss = v1.x * v2.y - v1.y * v2.x;
if (corss < 0) return -1;
return 1;
}
4.任意のポイントは、ポリゴン内にある
リンク:https://www.cnblogs.com/grassgarden/p/9250946.html
/// <summary>
/// 是否在多边形内部
/// </summary>
/// <param name="point"></param>
/// <param name="polygons"></param>
/// <returns></returns>
public static bool IsInPolygon(Vector3 point, Vector3[] polygons)
{
int nCross = 0;
Vector3 center = point;
//判断中点是否在多边形内部
for (int i = 0; i < polygons.Length; i++)
{
Vector3 next = polygons[(i + 1) % polygons.Length];
if (center.y < Mathf.Min(polygons[i].y, next.y)) continue;
if (center.y > Mathf.Max(polygons[i].y, next.y)) continue;
float x = (center.y - polygons[i].y) * (next.x - polygons[i].x) / (next.y - polygons[i].y) + polygons[i].x;
if (x > center.x)
++nCross;
}
//==1 表示终点在内部
if (nCross % 2 == 1)
return false;
return true;
}