You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GLSL片段着色器if-else语句失效问题求助

GLSL片段着色器if-else不生效问题解决

你遇到的问题核心是变量作用域冲突:在if和else代码块里,你用float u_col1重新声明了局部变量,这会屏蔽外部的uniform float u_col1。你给局部变量赋的值只在代码块内有效,出了块就失效了,最后gl_FragColor调用的还是最初的uniform变量值,所以红色通道始终没变化。

两种修正方案:

方案1:直接修改外部变量(去掉局部声明)

去掉代码块里的float关键字,直接给外部的u_col1赋值:

#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) {
        u_col1 = 0.1;
    } else {
        u_col1 = 1.0;
    }

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

方案2:使用局部变量承接结果(更规范)

因为uniform是CPU传入的全局变量,直接修改它在逻辑上不够严谨,更推荐声明一个局部变量来存储计算后的颜色值:

#ifdef GL_ES 
precision mediump float;
#endif

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

void main() {
    float redChannel;
    if (u_time >= 0.1) {
        redChannel = 0.1;
    } else {
        redChannel = 1.0;
    }

    gl_FragColor = vec4(redChannel, 0.0, 0.0, 1.0);
}

内容的提问来源于stack exchange,提问作者doingmybest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:00:55