0

在我的游戏中,我需要找出玩家触摸的位置。MotionEvent.getX() 和 MotionEvent.getY() 返回窗口坐标。所以我做了这个函数来测试将窗口坐标转换为OpenGL坐标:

public void ConvertCoordinates(GL10 gl) {
        float location[] = new float[4];

        final MatrixGrabber mg = new MatrixGrabber(); //From the SpriteText demo in the samples.
        mg.getCurrentProjection(gl);
        mg.getCurrentModelView(gl);

        int viewport[] = {0,0,WinWidth,WinHeight};

        GLU.gluUnProject((float) WinWidth/2, (float) WinHeight/2, (float) 0, mg.mModelView, 0, mg.mProjection, 0, viewport, 0, location,0);
        Log.d("Location",location[1]+", "+location[2]+", "+location[3]+"");
    }

X 和 y 从几乎 -33 振荡到几乎 +33。Z 通常是 10。我使用 MatrixGrabber 是不是错了?

4

2 回答 2

1

对我来说,最简单的方法是将屏幕上的点击想象为从相机位置开始并进入无限远的光线

为了得到那条光线,我需要在至少 2 个 Z 位置(在视图坐标中)询问它的世界坐标。

这是我找到射线的方法(我猜是取自同一个 android 演示应用程序)。它在我的应用程序中运行良好:

public void Select(float x, float y) {
    MatrixGrabber mg = new MatrixGrabber();
    int viewport[] = { 0, 0, _renderer.width, _renderer.height };

    _renderer.gl.glMatrixMode(GL10.GL_MODELVIEW);
    _renderer.gl.glLoadIdentity();
    // We need to apply our camera transformations before getting the ray coords 
    // (ModelView matrix should only contain camera transformations)
    mEngine.mCamera.SetView(_renderer.gl);

    mg.getCurrentProjection(_renderer.gl);
    mg.getCurrentModelView(_renderer.gl);

    float realY = ((float) (_renderer.height) - y);
    float nearCoords[] = { 0.0f, 0.0f, 0.0f };
    float farCoords[] = { 0.0f, 0.0f, 0.0f };
    gluUnProject(x, realY, 0.0f, mg.mModelView, 0, mg.mProjection, 0,
            viewport, 0, nearCoords, 0);
    gluUnProject(x, realY, 1.0f, mg.mModelView, 0, mg.mProjection, 0,
            viewport, 0, farCoords, 0);

    mEngine.RespondToClickRay(nearCoords, farCoords);
}

在 OGL10 AFAIK 中,您无法访问 Z-Buffer,因此您无法在屏幕 x,y 坐标处找到最近对象的 Z。您需要自己计算光线击中的第一个物体。

于 2011-04-29T07:21:26.010 回答
1

您的错误来自输出数组的大小。它们需要长度 4 而不是上面代码中的 3。

于 2011-09-14T19:39:46.867 回答