OpenGL ES (9): OpenGL ES 添加运动效果-旋转

1.介绍


上一篇文章讲到投影视图矩阵和相机视图变换,结合成新的矩阵mMVPMatrix传入给Triangle进行绘制。如下

private final float[] mMVPMatrix = new float[16]; //投影和相机结合的矩阵
private final float[] mProjectionMatrix = new float[16]; //投影矩阵
private final float[] mViewMatrix = new float[16]; //相机视图变换

这一次添加的旋转运动效果其实代码步骤和上面差不多,这次在渲染器中,再多添加一个新的变换矩阵(旋转矩阵),然后把它与你的投影与相机视图变换矩阵合并到一起。

//旋转矩阵
private float[] mRotationMatrix = new float[16];
public void onDrawFrame(GL10 gl) {
//上一篇文章的三个矩阵
     Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
      Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);


//新的结合矩阵
        float[] scratch = new float[16];

        //旋转的角度
        long time = SystemClock.uptimeMillis() % 4000L;
        float angle = 0.1f * ((int) time);
        Matrix.setRotateM(mRotationMatrix, 0, angle, 0, 0, -1.0f);

//把旋转矩阵和之前的结合矩阵mMVPMatrix结合生成新的结合矩阵scratch
        Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);

//传入新的结合矩阵,并绘制
        mTriangle.draw(scratch);
}

mTriangle.draw()方法不变,还是和之前一样。

public void draw(float[] mvpMatrix) {
        GLES20.glUseProgram(mProgram);
        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(
                mPositionHandle, COORDS_PER_VERTEX,
                GLES20.GL_FLOAT, false,
                vertexStride, vertexBuffer);

        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
        GLES20.glUniform4fv(mColorHandle, 1, color, 0);

//处理新的矩阵变换
        mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
        GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);

        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
        GLES20.glDisableVertexAttribArray(mPositionHandle);
    }

运行程序,可以看到一个不停转动的三角形.

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/83050003