unity中, 二维平面上,求从点A出发,沿着方向B,与线段C的交点

代码说明:

  • 点A:起始点。
  • 方向B:一个方向向量,表示从点A出发的方向。
  • 线段C:由两个点C1和C2定义。
 1 using UnityEngine;
 2 
 3 public class LineIntersection : MonoBehaviour
 4 {
 5     // 返回从点A出发,沿着方向B,与线段C的交点。如果没有交点,则返回null
 6     public static Vector2? GetIntersection(Vector2 A, Vector2 B, Vector2 C1, Vector2 C2)
 7     {
 8         // 方向向量
 9         Vector2 dirAB = B.normalized;  // 方向B是一个向量
10         Vector2 dirC = C2 - C1;
11 
12         // 定义线段C的法向量
13         Vector2 normalC = new Vector2(-dirC.y, dirC.x);
14 
15         // 计算AB与线段C的方向向量夹角的cos值(点积)
16         float denominator = Vector2.Dot(dirAB, normalC);
17         if (Mathf.Abs(denominator) < 1e-6)
18         {
19             // AB和线段C平行,没有交点
20             return null;
21         }
22 
23         // 计算参数t, t表示从A沿方向B移动到交点的比例
24         float t = Vector2.Dot(C1 - A, normalC) / denominator;
25 
26         if (t < 0)
27         {
28             // 交点在A的反方向,不考虑
29             return null;
30         }
31 
32         // 计算交点P
33         Vector2 P = A + t * dirAB;
34 
35         // 检查P是否在线段C上
36         float crossProduct = (P.x - C1.x) * (C2.y - C1.y) - (P.y - C1.y) * (C2.x - C1.x);
37         if (Mathf.Abs(crossProduct) > 1e-6)
38         {
39             // P不在线段C上
40             return null;
41         }
42 
43         float dotProduct = Vector2.Dot(P - C1, C2 - C1);
44         if (dotProduct < 0 || dotProduct > Vector2.Dot(C2 - C1, C2 - C1))
45         {
46             // P在延长线上,但不在线段C上
47             return null;
48         }
49 
50         return P;
51     }
52 }

 

使用方法:

调用GetIntersection函数来获取交点:

Vector2 A = new Vector2(0, 0);
Vector2 B = new Vector2(1, 1);
Vector2 C1 = new Vector2(1, 0);
Vector2 C2 = new Vector2(0, 1);

Vector2? intersection = LineIntersection.GetIntersection(A, B, C1, C2);

if (intersection != null)
{
    Debug.Log("Intersection Point: " + intersection.Value);
}
else
{
    Debug.Log("No Intersection.");
}

这段代码会找到从点A沿着方向B与线段C的交点,并在控制台输出交点的坐标。如果没有交点,则输出“没有交点”。

posted @ 2024-08-14 10:37  zerozabuu  阅读(6)  评论(0编辑  收藏  举报