2016-01-20 34 views
1

我試着計算交點平面和線,但我認爲得到錯誤的結果。 試試這個代碼(從http://wiki.unity3d.com/index.php/3d_Math_functions獲得):如何計算交點平面和線(Unity3d)

public static bool LinePlaneIntersection(out Vector3 intersection, Vector3 linePoint, Vector3 lineVec, Vector3 planeNormal, Vector3 planePoint) 
{ 
    float length; 
    float dotNumerator; 
    float dotDenominator; 
    Vector3 vector; 
    intersection = Vector3.zero; 

    //calculate the distance between the linePoint and the line-plane intersection point 
    dotNumerator = Vector3.Dot((planePoint - linePoint), planeNormal); 
    dotDenominator = Vector3.Dot(lineVec, planeNormal); 

    if (dotDenominator != 0.0f) 
    { 
     length = dotNumerator/dotDenominator; 

     vector = SetVectorLength(lineVec, length); 

     intersection = linePoint + vector; 

     return true; 
    } 

    else 
     return false; 
} 
+0

如果你爲了學習而去做,那麼繼續。如果你打算在遊戲中使用它,那麼也許你應該在那裏停下來,改用Physics.Raycast/Linecast。 – Everts

回答

1

,但我認爲得到錯誤的結果。

你能更具體嗎?

您使用的公式似乎是正確的;雖然我會用lineVec.noramlized * length而不是那個奇怪的SetVectorLength函數。

用於線路和平面的交點的基本公式是點x就行,其中的值是x由下式給出:

a = (point_on_plane - point_on_line) . plane_normal 
b = line_direction . plane_normal 

if b is 0: the line and plane are parallel 
if a is also 0: the line is exactly on the plane 
otherwise: x = a/b 

因此交點是:x * line_direction + line_point

這正是你的代碼雖然......所以...?

您可以閱讀wiki頁面這裏更多的細節:

https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection

編輯:其實,它看起來像這樣的代碼假設,如果dotDenominator是零,他們不相交;部分屬實;如果dotNumerator也爲零,則該線恰好位於該平面的頂部,並且所有點相交,因此可以將所需的任意點作爲交點(例如,planePoint)。

+0

我想弄清楚我在Unity編寫的着色器的計算:對於point_on_plane和point_on_line值,如果我的平面居中在0,0,0,我可以只使用'-point_on_line'部分?這只是一個任意點,或者是'開始'或'結束'?我很困惑... – moosefetcher