如何在GLES2.0中翻译相机?

如何在GLES2.0中翻译相机?

问题描述:

我想创建在平铺平面上方移动的摄像机。相机应该只在XY平面内移动,并且一直往下看。对于正交投影,我期望有一个伪2D渲染器。 我的问题是,我不知道如何翻译相机。经过一番研究,在我看来,OpenGL中没有像“相机”,我必须翻译整个世界。改变Matrix.setLookAtM-功能中的眼睛位置和视图中心坐标只会导致结果失真。 翻译整个MVP-Matrix也不起作用。如何在GLES2.0中翻译相机?

我现在想出来的想法;是否必须直接在顶点缓冲区中翻译每一帧的每个顶点?这对我来说似乎并不合理。

我得出GLSurfaceView并实现以下功能设置和更新场景:

public void onSurfaceChanged(GL10 unused, int width, int height) { 

    GLES20.glViewport(0, 0, width, height); 
    float ratio = (float) width/height; 

    // Setup the projection Matrix for an orthogonal view 
    Matrix.orthoM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7); 

} 

public void onDrawFrame(GL10 unused) { 

    // Draw background color 
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); 

    //Setup the camera 
    float[] camPos = { 0.0f, 0.0f, -3.0f }; //no matter what else I put in here the camera seems to point 
    float[] lookAt = { 0.0f, 0.0f, 0.0f }; // to the coordinate center and distorts the square 

    // Set the camera position (View matrix) 
    Matrix.setLookAtM(vMatrix, 0, camPos[0], camPos[1], camPos[2], lookAt[0], lookAt[1], lookAt[2], 0f, 1f, 0f); 

    // Calculate the projection and view transformation 
    Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, vMatrix, 0); 

    //rotate the viewport 
    Matrix.setRotateM(mRotationMatrix, 0, getRotationAngle(), 0, 0, -1.0f); 
    Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0); 

    //I also tried to translate the viewport here 
    // (and several other places), but I could not find any solution 

    //draw the plane (actually a simple square right now) 
    mPlane.draw(mMVPMatrix); 

} 

改变眼睛的位置,并在“注视” - 函数的观察中心坐标只是导致扭曲的结果。

如果你从android教程得到这个,我认为他们在他们的代码中有一个错误。 (做这件事here评论)

请尝试以下修正:

  1. 使用setLookatM以指向你想要的相机可以。
  2. 在着色器,改变gl_Position线

    来自:" gl_Position = vPosition * uMVPMatrix;"
    到:" gl_Position = uMVPMatrix * vPosition;"

  3. 我觉得//rotate the viewport部分也应该被删除,因为这是不正确的旋转摄像头。您可以在setlookat功能中更改相机的方向。

+0

是的,它基于您提到的官方示例中的代码。你的修复就像一个魅力。谢谢! – Andre 2012-08-15 20:55:15