c++3dtransparencyraylib

Draw transparent 3d object in raylib


I am new to c++ and raylib. The problem I am having is that when I try to draw a transparent cube or any 3d objects, it will use the ClearBackground color instead.

Here is a simple example:

#include <raylib.h>

int main() {

    const int screenWidth = 800;
    const int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person");

    Camera3D cam = { -2 ,2 ,0 };
    cam.fovy = 90;
    cam.up = (Vector3){ 0 ,1 ,0 };
    cam.target = (Vector3){ 0, 0, 0 };

    while (!WindowShouldClose())
    {
        // --- Update ---
        UpdateCamera(&cam, CAMERA_ORBITAL);

        // --- Draw ---
        BeginDrawing();

            ClearBackground(GRAY);

            BeginMode3D(cam);

                DrawSphere((Vector3){ -1, 0 ,0 }, .5, BLANK);
                DrawCubeWiresV((Vector3){ -1, 0 ,0 }, (Vector3){ 1, 1, 1 }, RED);
                DrawCubeWiresV((Vector3){ 1, 0 ,0 }, (Vector3){ 1, 1, 1 }, RED);

            EndMode3D();

        EndDrawing();
    }
    
    CloseWindow();

    return 0;
}

As you can see there is a "Sphere" with "BLANK" color. If you run the project you can see that the sphere is clearing every object behind it, so you can say "The sphere is using the background color instead of not being drawn".

NOTE: I want this because I want to use a semi-transparent color for glass in my game


Solution

  • Alpha blending is already enabled in raylib (check the BeginBlendMode function).

    To fix your problem you can just move the sphere (or any transparent object) later in the draw order. I'm not sure why this works but it might be that raylib bases the transparency on what has been already been drawn instead on the depth buffer.

    So instead of

    DrawSphere((Vector3){ -1, 0 ,0 }, .5, BLANK);
    DrawCubeWiresV((Vector3){ -1, 0 ,0 }, (Vector3){ 1, 1, 1 },
    DrawCubeWiresV((Vector3){ 1, 0 ,0 }, (Vector3){ 1, 1, 1 }, RED);
    

    Do

    DrawCubeWiresV((Vector3){ -1, 0 ,0 }, (Vector3){ 1, 1, 1 },
    DrawCubeWiresV((Vector3){ 1, 0 ,0 }, (Vector3){ 1, 1, 1 }, RED);
    DrawSphere((Vector3){ -1, 0 ,0 }, .5, BLANK);