Godot Version
4.3.stable
Question
Hello! I’m currently working on a 2D game and have been trying to implement a lighting shader, but it’s not working as intended.
The shader’s owner is a black ColorRect, and it works by “punching a hole” through the black screen to create a simple light circle.
I want the shader to be able to account for different light radius sizes, but it seems to be calculating only the first one.
I’m not experienced at writing shaders, so I have no idea what could be the problem (I got the code from a Youtube tutorial).
Please help! Shader provided below:
shader_type canvas_item;
//Remember to implement different light radius sizes.
uniform sampler2D screen_texture: hint_screen_texture, filter_nearest;
uniform vec2 lights[64];
uniform float light_radius[64];
uniform int number_of_lights = 1;
uniform vec4 modulate_color: source_color = vec4(0.0);
float distance_to_light(vec2 coords) {
float dist = 1000.0;
for (int i = 0; i < number_of_lights; i++) {
float new_dist = distance(coords, lights[i]);
if (new_dist < dist) {
dist = new_dist;
}
}
return dist;
}
vec4 modulate(vec4 color, float distance_to_light) {
vec4 modulated = color * modulate_color;
for (int i = 0; i < number_of_lights; i++) {
float radius = light_radius[i];
if (distance_to_light > radius) {
return modulated;
}
else {
float alpha = distance_to_light/radius;
return modulated * vec4(1, 1, 1, alpha);
}
}
return color;
}
void fragment() {
COLOR = texture(screen_texture, SCREEN_UV);
COLOR = modulate(COLOR, distance_to_light(FRAGCOORD.xy));
}
The “lights” and “light_radius” variables are set through code in the lighting layer node.