Home > OS >  OpenGL ES rotating shape around its center
OpenGL ES rotating shape around its center

Time:12-05

I tried to rotate rectangle using rotateMatrix, following tutorial on https://developer.android.com/training/graphics/opengl/motion, but when I runned it, the rectangle is rotating around (I think) point 0,0. What do I need to change to make it rotate around it's center?

@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);
}

CodePudding user response:

If you want to rotate around a pivot you have to:

  • Translate the object so that the pivot point is moved to (0, 0).
  • Rotate the object.
  • Move the object so that the pivot point moves in its original position.
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);

However, I recommend drawing the rectangle so that the center of the rectangle is at position (0, 0). Finally move the rectangle to its target position in the scene:

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);
  • Related