Shader won't work during runtime

Godot Version

4.2

Question

Hi everyone! In my godot game I have a shader that replaces the colors of the players sprite. It works in the editor but not during runtime. I don’t know why or if it’s because of 4.2.

Here is the shader code.

shader_type canvas_item;

uniform vec4 og_color : source_color;
uniform vec4 new_color : source_color;

uniform vec4 bright_color : source_color;
uniform vec4 new_bright : source_color;

void fragment() {
	vec4 curr_color = texture(TEXTURE, UV);

    // Define a threshold for the comparison
	if (COLOR == og_color){
		COLOR = new_color;
	}
	
	if (COLOR == bright_color){
		COLOR = new_bright;
	}
	
}
	


Thank you!

this looks simple enough, it basically replaces the color from specified uniform parameter, are you sure the color parameters have already changed during runtime? check the remote tab?

So, the shader works in the editor, but it doesn’t work during runtime, and nothing comes up in the remote tab.

This is because you’re performing floating-point comparison with exact values, which will break unexpectedly due to floating-point precision errors (just like in GDScript or C#). You need to introduce an epsilon value (here, 0.001) and check whether the value is within the range of this epsilon:

if (
    curr_color.r >= oldColor.r - 0.001 && curr_color.r <= oldColor.r + 0.001 &&
    curr_color.g >= oldColor.g - 0.001 && curr_color.g <= oldColor.g + 0.001 &&
    curr_color.b >= oldColor.b - 0.001 && curr_color.b <= oldColor.b + 0.001 && 
    curr_color.a >= oldColor.a - 0.001 && curr_color.a <= oldColor.a + 0.001
) {
    // Colors are approximately equal.
}

You can see more information about this here: Add `is_equal_approx()` and `is_zero_approx()` functions to the shader language · Issue #6870 · godotengine/godot-proposals · GitHub

1 Like

Thanks!