所以,似乎GLKit有GLKMathUnproject可以用来计算你在3D空间中点击的地方(真棒)
然而,我无法让它工作,我已经复制了一些不同的例子,它仍然没有检测到我在0,0,0点击我的立方体。我基本上做了下一个循环,看看我的光线是否击中了我的立方体。
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet* allTouches = [event allTouches];
UITouch*touch1 = [[allTouches allObjects] objectAtIndex:0];
CGPoint touch1Point = [touch1 locationInView:self.view];
GLKVector3 window_coord = GLKVector3Make(touch1Point.x,touch1Point.y, 0.0f);
bool result;
GLint viewport[4] = {};
glGetIntegerv(GL_VIEWPORT, viewport);
GLKVector3 near_pt = GLKMathUnproject(window_coord, _baseModelViewMatrix, _projectionMatrix, &viewport[0], &result);
window_coord = GLKVector3Make(touch1Point.x,touch1Point.y, 1.0f);
GLKVector3 far_pt = GLKMathUnproject(window_coord, _baseModelViewMatrix, _projectionMatrix, &viewport[0], &result);
//need to get z=0 from
//assumes near and far are on opposite sides of z=0
float z_magnitude = fabs(far_pt.z-near_pt.z);
float near_pt_factor = fabs(near_pt.z)/z_magnitude;
float far_pt_factor = fabs(far_pt.z)/z_magnitude;
GLKVector3 final_pt = GLKVector3Add( GLKVector3MultiplyScalar(near_pt, far_pt_factor), GLKVector3MultiplyScalar(far_pt, near_pt_factor));
float xDif = (final_pt.x - near_pt.x) / 1000;
float yDif = (final_pt.y - near_pt.y) / 1000;
float zDif = (final_pt.z - near_pt.z) / 1000;
for (int i = 0; i < 100; i ++)
{
if ((near_pt.x + (xDif * i)) > self.cube.position.x - self.cube.scale.x && (near_pt.x + (xDif * i)) < self.cube.position.x + self.cube.scale.x &&
(near_pt.y + (yDif * i)) > self.cube.position.y - self.cube.scale.y && (near_pt.y + (yDif * i)) < self.cube.position.y + self.cube.scale.y &&
(near_pt.z + (zDif * i)) > self.cube.position.z - self.cube.scale.z && (near_pt.z + (zDif * i)) < self.cube.position.z + self.cube.scale.z)
{
NSLog(@"%f %f %f", final_pt.x, final_pt.y, final_pt.z);
NSLog(@"Hit cube");
}
}
}
答案 0 :(得分:2)
我在这里找到了答案 Updating OpenGL ES Touch Detection (Ray Tracing) for iPad Retina?
- (void)handleTap: (UITapGestureRecognizer *)recognizer
{
CGPoint tapLoc = [recognizer locationInView:self.view];
tapLoc.x *= [UIScreen mainScreen].scale;
tapLoc.y *= [UIScreen mainScreen].scale;
bool testResult;
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
float uiKitOffset = 113; //Need to factor in the height of the nav bar + the height of the tab bar at the bottom in the storyboard.
GLKVector3 nearPt = GLKMathUnproject(GLKVector3Make(tapLoc.x, (tapLoc.y-viewport[3]+uiKitOffset)*-1, 0.0), modelViewMatrix, projectionMatrix, &viewport[0] , &testResult);
GLKVector3 farPt = GLKMathUnproject(GLKVector3Make(tapLoc.x, (tapLoc.y-viewport[3]+uiKitOffset)*-1, 1.0), modelViewMatrix, projectionMatrix, &viewport[0] , &testResult);
farPt = GLKVector3Subtract(farPt, nearPt);
....
}