簡體   English   中英

找到兩條線之間的交點

[英]Finding the intersection between two lines

所以我一直在思考這個相對簡單的算法。 我不確定我的代碼有什么問題,但我沒有得到它們實際相交的交點。

我正在使用 Unity3D 並且我試圖找到兩條線相交的點,在 x,z 平面中,但不在 x, y 平面中。 我假設適用於 x,y 的算法應該適用於 x,z;

我的代碼:

Vector3 thisPoint1 = thisCar.position + (2 * thisCar.forward);
Vector3 thisPoint2 = thisCar.position + (20 * thisCar.forward);

Debug.DrawLine(thisPoint1, thisPoint2, Color.white, 2);

Vector3 otherPoint1 = threateningCar.position + (2 * threateningCar.forward);
Vector3 otherPoint2 = threateningCar.position + (20 * threateningCar.forward);

Debug.DrawLine(otherPoint1, otherPoint2, Color.white, 2);

float A1 = thisPoint2.z - thisPoint1.z;
float B1 = thisPoint1.x - thisPoint2.x;
float C1 = A1 * thisPoint1.x + B1 * thisPoint1.z;

float A2 = otherPoint2.z - otherPoint1.z;
float B2 = otherPoint1.x - otherPoint2.x;
float C2 = A2 * otherPoint1.z + B2 * otherPoint1.z;

float det = A1 * B2 - A2 * B1;

float x = (B2 * C1 - B1 * C2) / det;
float z = (A1 * C2 - A2 * C1) / det;

return new Vector3(x, this.transform.position.y, z);

任何人都可以幫助指出我做錯了什么嗎?

thisCar.forwardthreateningCar.forward通常要么[0,0,1], [0,0,-1][1,0,0], [-1,0,0]

找到了!!!

float A2 = otherPoint2.z - otherPoint1.z;
float B2 = otherPoint1.x - otherPoint2.x;
float C2 = A2 * otherPoint1.z + B2 * otherPoint1.z;

應該:

float A2 = otherPoint2.z - otherPoint1.z;
float B2 = otherPoint1.x - otherPoint2.x; 

float C2 = A2 * otherPoint1 .x + B2 * otherPoint1.z

浪費了很多時間:/。

無論如何,這將幫助任何希望進行線交叉的人。

您可以將一個空的 GameObject 設置為汽車的父級,並將其稍微放在汽車的前面(在 IDE 中或在啟動時)。 這樣你就可以安全地得到畫一條線所需的兩個點。

如果你知道的距離t這款車需要旅行和u等車,然后交叉點是微不足道的。

Vector3 intersection = thisCar.position + (t * thisCar.forward);
Vector3 intersection = threateningCar.position + (u * threateningCar.forward);

但是您可以使用一些代數和 2D 矢量叉積來求解tu[x_1,z_1] × [x_2,z_1] = (x_2 z_1 - z_2 x_1)這是y 3D 叉積的標量值.

t = Vector3.Cross(threateningCar.forward, thisCar.position - threateningCar.position).y 
    / Vector3.Cross(thisCar.forward, threateningCar.forward).y;

u = Vector3.Cross(thisCar.forward, thisCar.position - threateningCar.position).y 
    / Vector3.Cross(thisCar.forward, threateningCar.forward).y;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM