我有一个仅包含 2D 对象的 OpenGL ES 2.0 场景。我正在应用以下两个矩阵:
width = 600;
CC3GLMatrix * projection = [CC3GLMatrix matrix];
height = width * self.frame.size.height / self.frame.size.width;
[projection populateFromFrustumLeft:-width/2 andRight:width/2 andBottom:-height/2 andTop:height/2 andNear:4 andFar:10];
glUniformMatrix4fv(_projectionUniform, 1, 0, projection.glMatrix);
CC3GLMatrix * modelView = [CC3GLMatrix matrix];
[modelView populateFromTranslation:CC3VectorMake(xTranslation ,yTranslation, -7)];
glUniformMatrix4fv(_modelViewUniform, 1, 0, modelView.glMatrix);
在 touches started 方法中,我尝试将触摸点坐标映射到 OpenGL ES 2.0 场景坐标:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"Touches Began");
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self];
float differentialWidth = (768-width)/2; //Accounts for if OpenGL view is less than iPad width or height.
float differentialHeight = (1024-height)/2;
float openGlXPoint = ((touchPoint.x - differentialWidth) - (width/2));
float openGlYPoint = ((touchPoint.y - differentialHeight) - (width/2));
NSLog(@"X in Scene Touched is %f", openGlXPoint);
CGPoint finalPoint = CGPointMake(openGlXPoint, openGlYPoint);
for (SquareObject * square in squareArray) {
if (CGRectContainsPoint(stand.bounds, finalPoint)) {
NSString * messageSquare = (@"Object name is %@", square.Name);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Touched"
message:messageSquare
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[message show];
}
}
}
此代码的工作原理是它返回 OpenGL 坐标 - 例如,单击屏幕中间成功返回 0,0。但是问题是(我认为)是我需要以某种方式考虑场景的缩放比例,因为以 150,0 为原点绘制的对象与我在 iPad 上单击的位置不匹配(返回 112,0使用上面的代码)。谁能建议我如何纠正这个问题?
谢谢 !