简体   繁体   English

GLSL 2D旋转矩阵无法正常工作

[英]GLSL 2D Rotation Matrix does not work as expected

I'm currently writing a game engine for 2D applications in C++. 我目前正在用C ++编写2D应用程序的游戏引擎。 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. 我不想使用GLM,所以我必须为自己编写一些东西。 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. 您可以计算精灵的一个角点(对于图元的所有顶点都相同),对其进行旋转,然后根据顶点ID通过添加x / y偏移量来构建轴对齐的矩形。 If you want to rotate the whole thing, you must apply the rotation after you calculated the actual rectangle corners. 如果要旋转整个对象,则必须在计算实际的矩形角后应用旋转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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