【问题标题】:glUnProject problem in AndroidAndroid中的glUnProject问题
【发布时间】:2011-04-27 01:27:58
【问题描述】:

在我的游戏中,我需要找出玩家触摸的位置。 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 还是什么?

【问题讨论】:

    标签: android opengl-es matrix model-view


    【解决方案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 缓冲区,因此您无法在屏幕 x,y 坐标处找到最近对象的 Z。 您需要自己计算光线击中的第一个物体。

    【讨论】:

    • 我正在尝试让它工作,但在 gluUnProject() 上收到错误:“07-14 13:51:36.620: ERROR/AndroidRuntime(14928): java.lang.IllegalArgumentException: length - offset
    【解决方案2】:

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

    【讨论】:

    • 这很好,但为什么? documentation 表明 obj 是一个大小为 3 的 x,y,z 数组。第四个元素是做什么用的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2016-10-19
    • 2011-11-16
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多