Android OpenGL weirdness with the setLookAtM method

陌路散爱 提交于 2019-12-06 05:24:51

问题


As a beginner to android and openGL 2.0 es, I'm testing simple things and see how it goes.

I downloaded the sample at http://developer.android.com/training/graphics/opengl/touch.html .

I changed the code to check if I could animate a rotation of the camera around the (0,0,0) point, the center of the square.

So i did this:

public void onDrawFrame(GL10 unused) {
    // Draw background color
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    // Set the camera position (View matrix)
    long time = SystemClock.uptimeMillis() % 4000L;
    float angle = ((float) (2*Math.PI)/ (float) 4000) * ((int) time);
    Matrix.setLookAtM(mVMatrix, 0, (float) (3*Math.sin(angle)), 0, (float) (3.0f*Math.cos(angle)),     0 ,0, 0,     0f, 1.0f, 0.0f);

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

    // Draw square
    mSquare.draw(mMVPMatrix);
}

I expected the camera to look always to the center of the square (the (0,0,0) point) but that's not what happens. The camera is indeed rotating around the square but the square does not stay in the center of the screen.. instead it is moving along the X axis...:

I also expected that if we gave the eyeX and eyeY the same values as centerX and centerY,like this:

Matrix.setLookAtM(mVMatrix, 0, 1, 1, -3,     1 ,1, 0,     0f, 1.0f, 0.0f);

the square would keep it's shape (I mean, your field of vision would be dragged but along a plane which would be paralel to the square), but that's also not what happens:

This is my projection matrix:

float ratio = (float) width / height;

// this projection matrix is applied to object coordinates
// in the onDrawFrame() method
Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 2, 7);

What is going on here?


回答1:


Looking at the source code to the example you downloaded, I can see why you're having that problem, it has to do with the order of the matrix multiplication.

Typically in OpenGL source you see matrices set up such that

transformed vertex = projMatrix * viewMatrix * modelMatrix * input vertex

However in the source example program that you downloaded, their shader is setup like this:

" gl_Position = vPosition * uMVPMatrix;"

With the position on the other side of the matrix. You can work with OpenGL in this way, but it requires that you reverse the lhs/rhs of your matrix multiplications.

Long story short, in your case, you should change your shader to read:

" gl_Position = uMVPMatrix * vPosition;"

and then I believe you will get the expected behavior.



来源:https://stackoverflow.com/questions/11924020/android-opengl-weirdness-with-the-setlookatm-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!