Implementing Transparency in Godot Shader When Intersecting with Semi-Transparent Objects

Godot 4.1

Hello everyone,

I’m working with a shader in Godot and have a specific requirement for which I need some guidance. Here’s the code snippet I’m currently using:

shader_type canvas_item;

uniform sampler2D SCREEN_TEXTURE : hint_screen_texture;
uniform sampler2D SPRITE_TEXTURE; // Texture of the sprite

void fragment() {
    vec4 screen_pixel = textureLod(SCREEN_TEXTURE, SCREEN_UV, 0.0);
    vec4 sprite_pixel = texture(SPRITE_TEXTURE, SCREEN_UV);

    if (screen_pixel.a <= 0.5) { // Checking if the pixel on the screen is transparent
        COLOR.a = 0.0;
    }
}

I want to achieve the following effect: the object should become transparent when it intersects with a semi-transparent object. Could you please advise on how to modify this shader to implement this functionality?

A thing that might help to know about when making shaders is that transparency is not fancy magic. When a layer of a shader has alpha < 1.0, it blends the previous color of the buffer and the new one with a very simple formula: foreground + background * (1 - foreground_alpha)
(the background always has 1.0 alpha, obviously)

As for how to determine if there was an object with transparency drawn before, you’re gonna have to keep a separate layer/buffer for that! just a single float on the pixel shader should do, tho, but you have to figure out when a certain texture is being actually drawn, and I’m not sure how you’d do that, but it’s definitely possible.

I hope this helps a little.