我已經在別處討論過這個話題,但在大多數情況下,解決方案提供者正在處理2D(正交)投影,因此它們會覆蓋Z值。我的世界具有以下特點:OpenGL ES(MonoTouch) - 手動實現gluUnProject奮鬥
- 透視投影
- 相機的 「向上」 矢量總是{0,1,0}
- 相機的Z座標總是正 (朝Z = 0看)
- 上我試圖確定命中點的平面爲Z = 0
我使用gluUnProject的端口,而我覺得我實現端口的是健全的,有可能肯定的東西那是錯的。但是,我希望問社區的是,如果我的算法看起來不正確。我在winZ = 0(近平面)和winZ = 1(遠平面)確定了世界座標。然後,我從這兩點確定射線,對其進行歸一化處理,並確定該射線的Z座標將爲0(在什麼點與Z = 0平面相交,這就是我所追求的)的值't' 。然而,問題在於我點擊這個原點(0,0,0)附近,但是一旦我開始點擊離開原點,誤差就會增加(例如,如果正確的世界座標應該爲爲50, 0,0他們實際上是85,0,0基於下面的計算。
如果低於這個過程是合理的,那麼我就可以開始調查我的實現gluUnProject的。
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
base.TouchesBegan (touches, evt);
var pt = (touches.AnyObject as UITouch).LocationInView(this);
int[] viewport = new int[4];
float[] proj = new float[16];
float[] model = new float[16];
GL.GetInteger(All.Viewport, viewport);
GL.GetFloat(All.ProjectionMatrix, proj);
GL.GetFloat(All.ModelviewMatrix, model);
float[] near = new float[3];
float[] far = new float[3];
Utils.gluUnProjectf(pt.X, viewport[3] - pt.Y, 0f, model, proj, viewport, out near);
Utils.gluUnProjectf(pt.X, viewport[3] - pt.Y, 1f, model, proj, viewport, out far);
Vector rayDirection = new Vector(far[0] - near[0], far[1] - near[1], far[2] - near[2]);
rayDirection.Normalize();
float t = (0 - near[2])/rayDirection.dZ;
Vertex end = new Vertex();
end.X = near[0] + rayDirection.dX * t;
end.Y = near[1] + rayDirection.dY * t;
end.Z = 0;
}