Godot着色器无法检测上方像素蓝色值并设为红色的问题
Godot CanvasItem着色器功能失效修复
我写的Godot CanvasItem着色器想实现这样的功能:检测当前像素上方像素的蓝色通道(b值),如果该值大于0.9,就把当前像素颜色设为红色,但这个功能一直没生效。
问题出在这段代码里:
else if (current.a < 0.1){ if (above.b > 0.9 && current.a > 0.9) { COLOR.rgba = RED; } }
我发现修改背景值时能检测到蓝色像素,但上方像素是蓝色时,当前像素不会变红。以下是完整的Shader代码:
shader_type canvas_item; void fragment() { vec4 below = texture(TEXTURE, UV + vec2(0.0, TEXTURE_PIXEL_SIZE.y)); vec4 above = texture(TEXTURE, UV - vec2(0.0, TEXTURE_PIXEL_SIZE.y)); vec4 current = texture(TEXTURE, UV); vec4 RED = vec4(1.0, 0.0, 0.0, 1.0); vec4 BLUE = vec4(0.0, 0.0, 1.0, 1.0); vec4 EMPTY = vec4(0.0, 0.0, 0.0, 0.0); COLOR = current; if (current.r > 0.9 && current.a > 0.9){ if (below.a < 0.1) { COLOR.rgba = BLUE; } } else if (current.b > 0.9 && current.a > 0.9) { if (below.r > 0.9 && current.a > 0.9) { COLOR.rgba = EMPTY; } } else if (current.a < 0.1){ if (above.b > 0.9 && current.a > 0.9) { COLOR.rgba = RED; } } }
问题分析
这段失效代码存在明显的逻辑冲突:外层判断条件是current.a < 0.1(当前像素透明),但内层又同时要求current.a > 0.9(当前像素完全不透明),这两个条件不可能同时满足,导致这个分支永远不会被执行。
修复方案
把内层的current.a > 0.9条件去掉,修改后的代码片段如下:
else if (current.a < 0.1){ if (above.b > 0.9) { COLOR.rgba = RED; } }
这样就能实现预期功能:当当前像素是透明状态,且上方像素的蓝色通道值大于0.9时,将当前像素设为红色。
内容的提问来源于stack exchange,提问作者No-one in particular
相关产品推荐
相关产品推荐

