Skip to content Skip to sidebar Skip to footer

Set Origin To Top-left Corner Of Screen In Opengl Es 2

I'm developing an Android app with OpenGL ES 2.0. It consists of a 2D HUD overlaid on a 3D scene. Everything is fine with the 3D part, but I cannot figure out how to position the o

Solution 1:

Is not a rule have only one mvpMatrix in OpenGL. It is good because you can customize a lot of views.

If all of your application is based in mvpMatrix that you showed here, I recommend you create another mvpMatrix for the proposal that you are asking: Make the center of the view in top-left corner.

So, the answer is simple, lets recreate every matrix. At first, viewMatrix:

Matrix.setLookAtM(viewMatrix, 0, 
     0, 0,  6,   //eye0, 0,  0,   //center0, 1,  0);  //UP *remove your -1

The magic is below. You have to invert bottom and top:

float screenRatio = (float) width / height;
Matrix.orthoM(projectionMatrix, 0, 
        0, screenRatio, // left, right1, 0,           // bottom, top        <----Solution is invert bottom with top-1, 10);        // near, far

And finally:

    Matrix.multiplyMM(
            viewProjectionMatrix, 0, 
            projectionMatrix, 0, 
            viewMatrix, 0);

P.S: don't need to change GLES20.glViewport(0, 0, surfaceWidth, surfaceHeight);

OpenGL have a lot of solution for this problem, because you can handle all matrix as you can.

Another solution is to customize your own matrix, without using Matrix.orthoM(..) or Matrix.frustum(..):

publicstaticfinalfloat[] topLeftMatrix(int width, int height){
    float matrix[] = newfloat[16];

    // This is inverse of viewPort matrix
    matrix[0] = 2.0f/width;
    matrix[1] = 0;
    matrix[2] = 0;
    matrix[3] = 0;

    matrix[4] = 0;
    matrix[5] = -2.0f/height;
    matrix[6] = 0;
    matrix[7] = 0;

    matrix[8] = 0;
    matrix[9] = 0;
    matrix[10] = 1;
    matrix[11] = 0;

    matrix[12] = -1;
    matrix[13] = 1;
    matrix[14] = 0;
    matrix[15] = 1;

    return matrix;
}

This matrix above is good for handling objects over pixels (like user-interface).

For full understanding, I recommend you read this article: 3D Graphics with OpenGL. It helped me a lot to understand the opengl magic.

P.S: there is an error in your shader. The correct way to multiply matrix4x4 by a vector 4x1 is:

gl_Position = uMVPMatrix * aPosition;

Post a Comment for "Set Origin To Top-left Corner Of Screen In Opengl Es 2"