I have a renderer implementing GLSurfaceView.Renderer interface; a subclass of GLSurfaceView and some classes representing my objects I want to draw. I have the code from ht
I´ve been working with the example from the Android Training, the following approach finally works for me. (Based on Android Training > Displaying Graphics with OpenGL ES > Adding Motion)
Use the correct vertex shader:
private final String vertexShaderCode =
// This matrix member variable provides a hook to manipulate
// the coordinates of the objects that use this vertex shader
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition;" +
"void main() {" +
// the matrix must be included as a modifier of gl_Position
" gl_Position = uMVPMatrix * vPosition;" +
"}";
In the renderer class:
public class MyGL20Renderer implements GLSurfaceView.Renderer {
[...]
// create a model matrix for the triangle
private final float[] mModelMatrix = new float[16];
// create a temporary matrix for calculation purposes,
// to avoid the same matrix on the right and left side of multiplyMM later
// see https://stackoverflow.com/questions/13480043/opengl-es-android-matrix-transformations#comment18443759_13480364
private float[] mTempMatrix = new float[16];
[...]
Apply transformations in onDrawFrame, start with translation:
public void onDrawFrame(GL10 unused) {
[...]
Matrix.setIdentityM(mModelMatrix, 0); // initialize to identity matrix
Matrix.translateM(mModelMatrix, 0, -0.5f, 0, 0); // translation to the left
Then rotation:
// Create a rotation transformation for the triangle
long time = SystemClock.uptimeMillis() % 4000L;
float mAngle = 0.090f * ((int) time);
Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
Combine rotation and translation, avoid using mModelMatrix
"as the same matrix on the right and left side of multiplyMM" (see 2)
// Combine Rotation and Translation matrices
mTempMatrix = mModelMatrix.clone();
Matrix.multiplyMM(mModelMatrix, 0, mTempMatrix, 0, mRotationMatrix, 0);
Combine the model matrix with the projection and camera view; again avoid using mModelMatrix
"as the same matrix on the right and left side of multiplyMM" (see 2)
// Combine the model matrix with the projection and camera view
mTempMatrix = mMVPMatrix.clone();
Matrix.multiplyMM(mMVPMatrix, 0, mTempMatrix, 0, mModelMatrix, 0);
Draw the shape
// Draw shape
mTriangle.draw(mMVPMatrix);
Thank you all, for all the useful input I could draw from this thread.