Search code examples
shadergodotgodot4alpha-transparencygodot-shader-language

In Godot4 (3D), how to make objects close to the camera transparent for a camera but not for another?


I am working on a 2 player cooperative game. Both of them are on a ship together. One of them is the pilot and another shoots a turret on the ship. The problem is that I would like to make the ship transparent for the turret to avoid obstructing its view, but not for the pilot. I can't change the material of the ship because that would make it transparent for both cameras. I set the turret's camera to clip nearby objects, which makes the ship disappear, and it helps clear the turret's view without altering the pilot's view of the ship. Is there any way to set the turret's view to make transparent instead of clipping nearby objects?


Solution

  • Without a bit more information regarding the way that you are currently implementing your node structure, it is difficult to say exactly what you need to do to get things working the way you are hoping. However, you can try a combination of the following techniques to achieve the camera transparency mechanic you're trying to create.

    1. Use Layers

    • Try adjusting the layer of the ship scene so that each camera can work with the layer uniquely.

    2. Use Viewports

    • Try using a new viewport/subviewport, one for the pilot, and one for the turret

    3. Use Shaders

    • Try writing a custom shader which can adjust the alpha level of the ship depending on the camera the shader is applied to. A very simple example shader to do this could look like the following (make sure you save this as a .shader file and assign it to a ShaderMaterial node, which you could then apply to the ship's MeshInstance in the turret's viewport):
    shader_type spatial;
    
    uniform bool is_turret_camera : hint_flag;
    
    void fragment() {
        if (is_turret_camera) {
            ALPHA = 0.5; // Just an example. Adjust as needed
        } else {
            ALPHA = 1.0;
        }
    }