简体   繁体   中英

GLSL 2D Rotation Matrix does not work as expected

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM