GLSL 2D Rotation Matrix does not work as expected Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of GLSL 2D Rotation Matrix does not work as expected without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m currently writing a game engine for 2D applications in C++. But at the moment I’m stuck with rotating the sprite in the vertex shader. I kind of followed this explaination. I don’t want to use GLM so I have to write some things for myself. At the moment, this is my texture shader.

Vertex Shader

out vec2 fragPos;
out vec2 fragUV;

uniform vec2 pos;
uniform vec2 size;
uniform float rotation;

void main(){
//gl_Position is OpenGL defined
gl_Position.z = 0.0;
gl_Position.w = 1.0;
gl_Position.x = vertPos.x + pos.x*2 - 1;
gl_Position.y = vertPos.y + pos.y*2 - 1;

mat4 rotationMat = mat4(cos(rotation), sin(rotation) * -1, 0, 0, 
                        sin(rotation), cos(rotation), 0, 0, 
                        0, 0, 1, 0, 
                        0, 0, 0, 1);


gl_Position *= rotationMat;

//vec2 size
if(size.x != 0 || size.y != 0){
    if(gl_VertexID != 0){
        switch(gl_VertexID){
            case 1: gl_Position.x += size.x; break;
            case 2: gl_Position.y += size.y; break;
            case 3: gl_Position.y += size.y; break;
            case 4: gl_Position.x += size.x; gl_Position.y += size.y; break;
            case 5: gl_Position.x += size.x; break;
        }
    }
}


fragPos = vertPos;
fragUV = vec2(vertUV.x, 1.0 - vertUV.y); 
}

No matter which value I pass, the rotation does not change. Only the position of the sprite. Here is how it looks like. Keep in mind that the texture is supposed to be so squished. I also checked this question, but it didn’t help at all. I anyone knows why my texture does not want to rotate itself!

Answer

No matter which value I pass, the rotation does not change. Only the position of the sprite.

That’s exactly what your code does. You calculate one corner point of your sprite (which is the same for all vertices of the primitive), apply a rotation to that, and then build an axis-aligned rectangle by adding an x/ y offset depending on the vertex ID. If you want to rotate the whole thing, you must apply the rotation after you calculated the actual rectangle corners.

We are here to answer your question about GLSL 2D Rotation Matrix does not work as expected - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji