Ievgen
Ievgen

Reputation: 4443

How to move opengl triangle in default android sample?

I am using default android sample code http://developer.android.com/training/graphics/opengl/touch.html In this sample we can rotate triangle by toucht events.

I want just to add movement by x,y axiss for test purposes. The point that triangle behaviour is not as i am expecting. What i am doing wrong?

Code from tutorial with my new row hilighted:

public void onDrawFrame(GL10 unused) {

        // Draw background color
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        // Set the camera position (View matrix)
        Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

        // Calculate the projection and view transformation
        Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);


        // Draw square
        mSquare.draw(mMVPMatrix);



       **//Translating this matrix 'brakes' triangle
  ->      Matrix.translateM(mMVPMatrix, 0, 0, pos, -1.0f);

        //NOTHING happens here: ??? Why?
  ->      Matrix.translateM(mRotationMatrix, 0, pos, 0, -1.0f);**

        // Create a rotation for the triangle
        // long time = SystemClock.uptimeMillis() % 4000L;
        // float angle = 0.090f * ((int) time);
        Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);

        // Combine the rotation matrix with the projection and camera view
        Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0);

        // Draw triangle
        mTriangle.draw(mMVPMatrix);
    }

Default behaviour:

enter image description here

With my code:

enter image description here

Upvotes: 0

Views: 3062

Answers (1)

Ievgen
Ievgen

Reputation: 4443

Thanks for a icrev comment:

You can not do translation / rotation / scaling on MVP matrix and get results as you expect.

you must translate / rotate your object in model matrix (or in View matrix for camera trans/rotation).

Look at this The purpose of Model View Projection Matrix to understand better what you need to do

These are the steps:

  1. set M matrix to Identity matrix. Translate or rotate it. Be aware of gimbal lock (en.wikipedia.org/wiki/Gimbal_lock)

  2. set V matrix Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f); 3. you already have projection matrix (in your case mProjMatrix)

    1. multippy M * V * P to recieve final MVP matrix

Upvotes: 1

Related Questions