簡體   English   中英

Unity3d:放置一個游戲對象,使其與其他兩個游戲對象形成一個直角三角形

[英]Unity3d: Position a gameobject such that its forms a right angled triangle with other two gameobjects

在此處輸入圖片說明

我如何定位C gameObject ,使其與A and B形成一個直角三角形。 我嘗試使用(B.transform.position.x,A.transform.position.z)但它仍然給我一些接近A東西(它需要全局)。 我希望C沿着local red axis of Alocal red axis of Alocal green axis of B如圖所示。 我該怎么辦?

有幾種方法可以表達這個問題。


一種是沿 B 的上軸找到這樣一個點,使其與 A 成直角。這將忽略 A 的任何旋轉。

為此,請沿 B 向上投影 A 的位置。 換句話說,找到 (AB) 和 B's up 的點積,乘以 B's up,然后將其添加到 B。

Vector3 cPos = B.transform.position + Vector3.Dot(A.transform.position - B.transform.position, B.transform.up) * B.transform.up;
C.transform.position = cPos;

另一種方法是找到 B 向上和 A 向右的交點。 根據 A 和 B 的旋轉,這可能會產生非直角或可能根本沒有點。

這個有點復雜,評論里的鏈接有很好的實現:

 public static bool LineLineIntersection(out Vector3 intersection, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2){ Vector3 lineVec3 = linePoint2 - linePoint1; Vector3 crossVec1and2 = Vector3.Cross(lineVec1, lineVec2); Vector3 crossVec3and2 = Vector3.Cross(lineVec3, lineVec2); float planarFactor = Vector3.Dot(lineVec3, crossVec1and2); //is coplanar, and not parrallel if(Mathf.Abs(planarFactor) < 0.0001f && crossVec1and2.sqrMagnitude > 0.0001f) { float s = Vector3.Dot(crossVec3and2, crossVec1and2) / crossVec1and2.sqrMagnitude; intersection = linePoint1 + (lineVec1 * s); return true; } else { intersection = Vector3.zero; return false; } }

然后找到你的位置:

Vector3 cPos;
bool doIntersect = LineLineIntersection(out cPos, A.transform.position, A.transform.right, B.transform.position, B.transform.up);
if (doIntersect) {
    C.transform.position = cPos;
} else {
    // do something reasonable, like using projection, or not changing the position
    Vector3 cPos = B.transform.position + Vector3.Dot(A.transform.position - B.transform.position, B.transform.up) * B.transform.up;
    C.transform.position = cPos;
}

暫無
暫無

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

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