OpenGL ES 围绕其中心旋转形状

OpenGL ES rotating shape around its center

我尝试按照 https://developer.android.com/training/graphics/opengl/motion 上的教程使用 rotateMatrix 旋转矩形,但是当我运行它时,矩形围绕(我认为)点 0,0 旋转。我需要更改什么才能使其围绕中心旋转?

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    MainGLRenderer.width = width;
    MainGLRenderer.height = height;

    loadLevel();

    GLES20.glViewport(0, 0, width, height);

    Matrix.orthoM(projectionMatrix, 0, 0, width, height, 0, 1, -1);
    Matrix.setLookAtM(viewMatrix, 0, 0, 0, 1, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
    Matrix.multiplyMM(mvpMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
}

@Override
public void onDrawFrame(GL10 gl) {
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

    float[] scratch = new float[16];
    long time = SystemClock.uptimeMillis() % 4000L;
    float angle = 0.090f * ((int) time);
    Matrix.setRotateM(rotationMatrix, 0, angle, 0, 0, -1.0f);
    Matrix.multiplyMM(scratch, 0, mvpMatrix, 0, rotationMatrix, 0);

    rectangle.x = 200;
    rectangle.y = 200;
    rectangle.w = 200;
    rectangle.h = 200;
    rectangle.draw(scratch);
}

如果你想围绕一个枢轴旋转你必须:

  • 平移对象,使轴心点移动到 (0, 0)。
  • 旋转对象。
  • 移动对象,使轴心点移动到其原始位置。
float pivotX = 300;
float pivotY = 300;
Matrix.setIdentityM(rotationMatrix, 0);
Matrix.translateM(rotationMatrix, 0, pivotX, pivotY, 0);
Matrix.rotateM(rotationMatrix, 0, angle, 0, 0, -1.0f);
Matrix.translateM(rotationMatrix, 0, -pivotX, -pivotY, 0);

但是,我建议绘制矩形,使矩形的中心位于位置 (0, 0)。最后将矩形移动到场景中的目标位置:

Matrix.setIdentityM(rotationMatrix, 0);
Matrix.translateM(rotationMatrix, 0, pivotX, pivotY, 0);
Matrix.rotateM(rotationMatrix, 0, angle, 0, 0, -1.0f);
Matrix.multiplyMM(scratch, 0, mvpMatrix, 0, rotationMatrix, 0);

rectangle.x = -100;
rectangle.y = -100;
rectangle.w = 200;
rectangle.h = 200;
rectangle.draw(scratch);