基本思路是先求過圓心的直線的垂線吝梅,在判斷點(diǎn)線距離和半徑的大小來判斷有沒有交點(diǎn)查蓉,如果有交點(diǎn)丰介,用與垂線的交點(diǎn)加上或減去弦長的一半乘以直線的方向向量舵抹。
private static Vector2 CalIntersection(Vector2 start, Vector2 end, Vector2 center)
{
Vector2 v = Vector2.zero;
float disY1 = end.y - start.y;
float disX1 = end.x - start.x;
//平行于x軸
if (disY1.Approximately(0.0f))
{
v.x = center.x;
v.y = start.y;
return v;
}
//平行于y軸
if (disX1.Approximately(0.0f))
{
v.x = start.x;
v.y = center.y;
return v;
}
float k1 = (end.y - start.y) / (end.x - start.x);
float b1 = start.y - k1 * start.x;
float k2 = 1.0f / -k1;
float b2 = center.y - k2 * center.x;
v.x = (b2 - b1) / (k1 - k2);
v.y = k1 * v.x + b1;
return v;
}
//弦長的一半
private static float GetSpringLength(float radius, Vector2 center, Vector2 v1)
{
float a = 0;
float lengthToCenter = (center - v1).sqrMagnitude;
float sqrSpringLength = radius * radius - lengthToCenter;
//無交點(diǎn)
if (sqrSpringLength < 0)
{
return -1;
}
return (float) Math.Sqrt(sqrSpringLength);
}
Vector2 inter = CalIntersection(start.GetXZ(), end.GetXZ(), center.GetXZ());
float length = GetSpringLength(radius, center.GetXZ(), inter);
if (length < 0)
{
return end;
}
var nor = (end - start).normalized;
var p = inter + (nor.GetXZ() * length);