Bogudał.Mikołaj
Bogudał.Mikołaj

Reputation: 543

Strange behevior when translating and rotating in the same axis

Im trying to rotate object in OpenGL ES around its center. When i use Matrix.translateM() on the same axis what Matrix.setRotatem() it changing my object center to 0 on this axis. When i trying operation below:

Matrix.translateM(rotationMatrix, OFFSET, 0, 1, 0);
Matrix.setRotateM(rotationMatrix, OFFSET, 90, 0, 1, 0);
Matrix.translateM(rotationMatrix, OFFSET, 0, -1, 0);

Then effect is: enter image description here

But when i do something like this:

Matrix.translateM(rotationMatrix, OFFSET, 0, 0, 0);
Matrix.setRotateM(rotationMatrix, OFFSET, 90, 0, 1, 0);
Matrix.translateM(rotationMatrix, OFFSET, 0, 0, 0);

Effect is: enter image description here

The second picture it's a correct look. So, my question is: Why translating on y axis, creates this mess.

Upvotes: 1

Views: 176

Answers (1)

Rabbid76
Rabbid76

Reputation: 210918

If you want to rotate an object around a pivot then you've to:

  • Translate the object in that way that way, that the pivot is on the origin (0, 0, 0).
    Since your object is located at (0, 1, 0) this means the object has to be translated by (0, -1, 0).

  • Rotate the object. If the object has to be rotated in the projection plane to the screen, then the rotation axis has to be the z axis (0, 0, 1). If the object hast to be rotated around an vertical axis, then the rotation axis has to be the z axis (0, 1, 0). For a rotation around a horizontal axis, the object has to be rotated around the x axis (0, 1, 0).

  • Translate the rectangle in that way that the pivot is back at its original position.
    This means the object has to be translated by (0, 1, 0).

rotationMatrix = translate(0, 1, 0) * rotate * translate(0, -1, 0)

You've to use the Matrix operations Matrix.translateM respectively Matrix.rotateM, which create a new matrix and multiply the input matrix by the new matrix:

private float[] rotationMatrix = new float[16];
Matrix.setIdentityM(rotationMatrix, 0);

Matrix.translateM(rotationMatrix, 0, 0, 1, 0);
Matrix.rotateM(rotationMatrix, 0, 90, 0, 0, 1);
Matrix.translateM(rotationMatrix, 0, 0, -1, 0);

Note, the rotation axis are the last 3 parameters of Matrix.rotateM. You've to set them for your needs.

Upvotes: 1

Related Questions