glslglsles

Glsl fragment - if else statements


Absolute beginner question here as you can guess. I'm trying to implement the most basic if else statement in my fragment shader, I have no error message but the first value of my vec4 color vector isn't changing at all.

#ifdef GL_ES 
precision mediump float;
#endif

uniform float u_time;
uniform vec2 u_resolution;
uniform float u_col1;

void main() {
    

    if ( u_time >= 0.1 )
    {
        float u_col1 = 0.1;
    } else {
        float u_col1 = 1.;
    }

gl_FragColor = vec4(u_col1,0.0,0.0,1.0);

}

Solution

  • You must declare a local variable before the if-else-statement and change that variable in the if-else-statement (this works like in most other programming languages):

    #ifdef GL_ES 
    precision mediump float;
    #endif
    
    uniform float u_time;
    uniform vec2 u_resolution;
    
    void main() {
        
        float u_col1;
        if ( u_time >= 0.1 ) {
            u_col1 = 0.1;
        } else {
            u_col1 = 1.;
        }
        gl_FragColor = vec4(u_col1,0.0,0.0,1.0);
    }