投影和相机视图不适用于OpenGL

时间:2014-06-25 11:37:15

标签: android view opengl-es camera projection

我试图应用投影和相机视图,但我没有得到想要的结果。当我将设备从纵向模式旋转到横向模式时,绘制的三角形仍会变形。这是我的Triangle类中的draw()方法:

public void draw(float[] mvpMatrix) {

      int vertexCount = 3;
      int vertexStride = 3 * COORDS_PER_VERTEX;
      int mMVPMatrixHandle;



        // Add program to OpenGL ES environment
        GLES20.glUseProgram(mProgram);


        // get handle to vertex shader's vPosition member
        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
        // get handle to shape's transformation matrix
        mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");



        // Enable a handle to the triangle vertices
        GLES20.glEnableVertexAttribArray(mPositionHandle);


        // Prepare the triangle coordinate data
        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
                                     GLES20.GL_FLOAT, false,
                                     vertexStride, vertexBuffer);
     // Pass the projection and view transformation to the shader
        GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);

        // get handle to fragment shader's vColor member
        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");

        // Set color for drawing the triangle
        GLES20.glUniform4fv(mColorHandle, 1, color, 0);

        // Draw the triangle
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);

        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);

    }

我不知道它为什么不起作用,还有来自Renderer类的onDrawFrame()和onSurfaceChanged()方法:

private float[] mProjectionMatrix = new float[16]   
private float[] mViewMatrix = new float[16];                                     
private float[] mMVPMatrix = new float[16];




public void onDrawFrame(GL10 unused) {
    // Redraw background color
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);


    // Set the camera position (View matrix)
    Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);


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

    // Draw shape
    mTriangle.draw(mMVPMatrix);


}

public void onSurfaceChanged(GL10 unused, int width, int height) {
    GLES20.glViewport(0, 0, width, height);

    float ratio = (float) width / height;

    // this projection matrix is applied to object coordinates
    // in the onDrawFrame() method

    Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
}

1 个答案:

答案 0 :(得分:0)

缺少一些代码,这里应该添加:

private final String vertexShaderCode = 

    "uniform mat4 uMVPMatrix;" +
    "attribute vec4 vPosition;" +
    "void main() {" +
    "  gl_Position = vPosition * uMVPMatrix;" +
    "}";