在我的iOS应用程序中,我将纹理应用于OpenGLES1中渲染的球体。用户可以旋转球体。如何在任何给定时间跟踪纹理上给定点在2D空间中的位置?

例如,给定点(200,200)在1000px x 1000px的纹理上,我想将UIButton放置在我的OpenGL视图顶部,该按钮在操纵球体时跟踪该点。

最好的方法是什么?

第一次尝试时,我尝试使用一种颜色选择技术,其中在屏幕外的帧缓冲区中有一个单独的球体,该球体使用黑色纹理和点(200,200)的红色正方形。然后,我使用glReadPixels()跟踪红色正方形的位置,并相应地移动了按钮。不幸的是,由于明显的性能原因,无法捕获所有像素数据并每秒对其进行60次迭代。我尝试了多种方法来优化此技巧(例如:仅迭代红色像素,每第4个红色像素迭代等等),但事实证明它并不可靠。

我是OpenGL菜鸟,因此不胜感激。有更好的解决方案吗?谢谢!

最佳答案

我认为追踪球的位置比用像素搜索球更容易。然后,只需几个函数即可将球的坐标转换为视图的坐标(并向后),然后将子视图的中心设置为转换的坐标。

CGPoint translatePointFromGLCoordinatesToUIView(CGPoint coordinates, UIView *myGLView){

    //if your drawing coordinates were between (horizontal {-1.0 -> 1.0} vertical {-1 -> 1})
    CGFloat leftMostGLCoord       = -1;
    CGFloat rightMostGLCoord      = 1;
    CGFloat bottomMostGLCoord     = -1;
    CGFloat topMostGLCoord        = 1;

    CGPoint scale;
    scale.x = (rightMostGLCoord - leftMostGLCoord) / myGLView.bounds.size.width;
    scale.y = (topMostGLCoord - bottomMostGLCoord) / myGLView.bounds.size.height;


    coordinates.x -= leftMostGLCoord;
    coordinates.y -= bottomMostGLCoord;


    CGPoint translatedPoint;
    translatedPoint.x = coordinates.x / scale.x;
    translatedPoint.y =coordinates.y / scale.y;

    //flip y for iOS coordinates
    translatedPoint.y = myGLView.bounds.size.height - translatedPoint.y;

    return translatedPoint;
}

CGPoint translatePointFromUIViewToGLCoordinates(CGPoint pointInView, UIView *myGLView){

    //if your drawing coordinates were between (horizontal {-1.0 -> 1.0} vertical {-1 -> 1})
    CGFloat leftMostGLCoord       = -1;
    CGFloat rightMostGLCoord      = 1;
    CGFloat bottomMostGLCoord     = -1;
    CGFloat topMostGLCoord        = 1;

    CGPoint scale;
    scale.x = (rightMostGLCoord - leftMostGLCoord) / myGLView.bounds.size.width;
    scale.y = (topMostGLCoord - bottomMostGLCoord) / myGLView.bounds.size.height;

    //flip y for iOS coordinates
    pointInView.y = myGLView.bounds.size.height - pointInView.y;

    CGPoint translatedPoint;
    translatedPoint.x = leftMostGLCoord + (pointInView.x * scale.x);
    translatedPoint.y = bottomMostGLCoord + (pointInView.y * scale.y);

    return translatedPoint;
}

在我的应用程序中,我也选择对图形使用iOS坐标系。我只是将投影矩阵应用于整个glkView,以协调坐标系。
static GLKMatrix4 GLKMatrix4MakeIOSCoordsWithSize(CGSize screenSize){
    GLKMatrix4 matrix4 = GLKMatrix4MakeScale(
                                             2.0 / screenSize.width,
                                             -2.0 / screenSize.height,
                                             1.0);
    matrix4 = GLKMatrix4Translate(matrix4,-screenSize.width / 2.0, -screenSize.height / 2.0, 0);

    return matrix4;
}

这样,您无需翻译任何内容。

10-05 17:45
查看更多