I am trying to rotate an object in Open GL. I can successfully draw a square, but when I try to rotate it stays in the same place. I have tried to move around the order of the lines below but still doesn't work, (doesn't draw at all with certain order or certain lines removed)... here's the code i have so far, mAngle is a random float between 0 and 360.
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.setRotateM(mModelMatrix, 0, mAngle, 0f, 0f, 1.0f);
Matrix.setLookAtM(mModelMatrix, 0, 0, 0, 5f, 0f, 0f, 0f, 0f, 10.0f, 0.0f);
Matrix.translateM(mModelMatrix, 0, 0f, 0f, 0f);
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mModelMatrix, 0);
mSquare.draw(mMVPMatrix);
Matrix.setRotateM
creates a new matrix for rotation by angle a (in degrees) around the axis (x, y, z).
Matrix.setLookAtM
defines a new viewing transformation in terms of an eye point, a center of view, and an up vector.
Both operations do not manipulate a input matrix, they create a complete new matrix by their parameters and write it to the output rm
.
In compare, with Matrix.rotateM
a given matrix is rotated.
You have to create a separated view matrix by Matrix.setLookAtM
:
Matrix viewM = new Matrix();
Matrix.setLookAtM(viewM, 0, 0, 0, 5f, 0f, 0f, 0f, 0f, 10.0f, 0.0f);
and you have to multiply it to the roation matrix (model matrix) by Matrix.multiplyMM
:
Matrix.multiplyMM(mModelMatrix, 0, viewM, 0, modelM, 0);
I recommend writing the code like this:
Matrix modelM= new Matrix();
Matrix.setRotateM(modelM, 0, mAngle, 0f, 0f, 1.0f);
Matrix viewM = new Matrix();
Matrix.setLookAtM(viewM, 0, 0, 0, 5f, 0f, 0f, 0f, 0f, 10.0f, 0.0f);
Matrix.multiplyMM(mModelMatrix, 0, viewM, 0, modelM, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mModelMatrix, 0);