Change color with Shader

Godot Version

4.3

Question

Hi guys, i was working on my game and i finally got a good shader to work. My red crab was finally green, keeping all the shades and details!
I close godot, eat, get back to godot and… to my horror there’s a very little mistake in line 3 of the shader code.

shader_type canvas_item;

uniform vec4 source_color = vec4(1.0, 0.0, 0.0, 1.0); // Starting color (e.g., red)
uniform vec4 target_color = vec4(0.0, 1.0, 0.0, 1.0); // Target color (e.g., green)
uniform float threshold = 0.2; // Threshold to identify the starting color
uniform float blend_amount = 1.0; // Intensity of the modification
uniform float brightness = 0.0; // Brightness (-1.0 to 1.0)
uniform float contrast = 1.0; // Contrast
uniform float saturation = 1.0; // Saturation
uniform vec2 texture_size = vec2(256.0, 256.0); // Texture size

void fragment() {
vec4 tex_color = texture(TEXTURE, UV); // Original texture color

// Calculate the difference between the pixel color and the starting color
float color_diff = distance(tex_color.rgb, source_color.rgb);

// Determine if the pixel is close to the starting color
float is_match = smoothstep(threshold, threshold * 1.5, 1.0 - color_diff);

// Increase the target color's brightness to prevent it from being too dark
float luminance = dot(tex_color.rgb, vec3(0.299, 0.587, 0.114));
vec3 boosted_target = target_color.rgb * (luminance + 1.0 + brightness);

// Apply saturation
float current_luminance = dot(boosted_target, vec3(0.299, 0.587, 0.114));
boosted_target = mix(vec3(current_luminance), boosted_target, saturation);

// Apply contrast
boosted_target = (boosted_target - 0.5) * contrast + 0.5;

// Blend the original color with the target color
vec3 modified_color = mix(tex_color.rgb, boosted_target, is_match * blend_amount);

COLOR = vec4(modified_color, tex_color.a);

}

I spent an entire day trying to fix it. It worked this morning: i saw it, i’m not hallucinating… or maybe i am? Maybe i’m going crazy. Maybe it’s all a bad dream!
I’ll accept any kind of help. If someone has a good shader to change color of an animatedsprite2d it would be great.
I also tried getting rid of the shader putting everything on a script merging the shader with this script:
extends AnimatedSprite2D

Exported variables for HEX colors

u/export var source_color_hex: Color = Color(“ff0000”) # Source color (red)
u/export var target_color_hex: Color = Color(“00ff00”) # Target color (green)

func _ready():
update_shader_colors()

func _process(_delta):
update_shader_colors()

func update_shader_colors():
# Update shader parameters with the converted HEX values
if material and material is ShaderMaterial:
material.set_shader_parameter(“source_color”, source_color_hex)
material.set_shader_parameter(“target_color”, target_color_hex)

Not sure if it helps, but I have this shader to modify colors:

1 Like