我正在尝试GLKMathUnproject()
将屏幕坐标转换为几何图形,但我的例程总是返回屏幕中心的任何几何图形。
我的 unproject 代码如下所示:
+ (GLKVector3) gluUnproject: (GLKVector3) screenPoint
inView: (UIView*) view
withModelMatrix: (GLKMatrix4) model
projection: (GLKMatrix4) projection
{
CGSize viewSize = view.bounds.size;
int viewport[4];
viewport[0] = 0.0f;
viewport[1] = 0.0f;
viewport[2] = viewSize.width;
viewport[3] = viewSize.height;
bool success;
GLKVector3 result = GLKMathUnproject(screenPoint, model, projection, &viewport[0], &success);
return result;
}
我对它的调用如下所示:
- (void) handleSingleTap: (UIGestureRecognizer*) sender
{
UITapGestureRecognizer *tapper = (UITapGestureRecognizer*) sender;
CGPoint tapPoint = [tapper locationInView: self.view];
// Find tapped point on geometry
MyObject *bd = [worldObjects objectAtIndex: 0]; // the object on which I'm trying to sense the tap.
// NOTE: bd is planar, along X/Z, with Y=0. Visually, it's several little
// ..squares (like a big checkerboard), and I'm trying to determine
// ..in which square the user tapped.
// At this point. eyesAt is { someX, y, someZ } and lookAt is { someX, 0, someZ } and
// ..upVector is { 0, 0, -1 }. We Zoom our view of the board in/out by
// ..changing eyesAt.y
float tapZ = (self.eyesAt.y - self.zNear) / (self.zFar - self.zNear); // % of the Z-depth. eyesAt.y = distance to geometry.
GLKVector3 tapPoint3 = GLKVector3Make(tapPoint.x, tapPoint.y, tapZ);
GLKVector3 tapAt = [MFglkUtils gluUnproject: tapPoint3 inView: self.view withModelMatrix: bd.modelviewMatrix projection: [self projectionMatrix]];
// etc., snip -- do stuff with the tapAt point.
问题是:gluUnproject
无论我点击哪里,我总是返回屏幕中间的几何点。
编辑: “总是靠近中心”的问题是返回的 X/Z 值总是非常接近于零,并且我的几何图形以原点为中心。
看来问题出在我的tapZ
价值上。我的理解是,这应该是一个 0-1 的值,其中 0 表示“在 nearZ 平面”,1 表示“在 farZ 平面”,中间值是介于两者之间的百分比。尝试各种tapZ
值,我已经看到:
// gives very-very small results
tapZ = (self.eyesAt.y - self.zNear) / (self.zFar - self.zNear); // % deep through the view frustum
// gives Z=0, and very small results
glReadPixels(viewPoint.x, viewPoint.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &tapZ);
// gives approximately-correct results
tapZ = 0.99943; // found through trial & error
// gives Z=1, and too-big results
glReadPixels(viewPoint.x, viewPoint.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &tapZ);
tapZ = 1. - tapZ;
显然,我需要传递一个正确的tapZ
值,但我不明白如何得出它!