Search code examples
javajavafx3dtransparency

How to make a JavaFX 3D Box transparent


I am trying to make the 3D Box to be transparent that I can see through. I am using the following code to make it.

Box truck = new Box(Truck.WIDTH, Truck.HEIGHT, Truck.DEPTH);
truck.setTranslateX(Truck.WIDTH >> 1);
truck.setTranslateY(Truck.HEIGHT >> 1);
truck.setTranslateZ(Truck.DEPTH >> 1);
truckMaterial.setDiffuseColor(Color.SILVER.deriveColor(.3, .3, 0.4, .3));
truck.setMaterial(truckMaterial);

group = new Group();
group.getChildren().add(truck);

mainScene = new SubScene(group, SCREEN_WIDTH * .75, SCREEN_HEIGHT, true, SceneAntialiasing.BALANCED);
mainScene.setFill(Color.SILVER);

// set up the camera
Camera camera = new PerspectiveCamera();
camera.translateXProperty().set(Truck.WIDTH - ((mainScene.getWidth() / 2) + (SCREEN_WIDTH / 2)));
camera.translateYProperty().set(Truck.HEIGHT - (mainScene.getHeight() / 2));
camera.translateZProperty().set(-(Truck.DEPTH / 0.2));
mainScene.setCamera(camera);

This line truckMaterial.setDiffuseColor(Color.SILVER.deriveColor(.3, .3, 0.4, .3)); supposed to make it transparent. The material is truckMaterial = new PhongMaterial();

Any help would be appreciated.


Solution

  • Just set the opacity of the diffuseMaterial to a non-opaque color. Set the opacity of the color below 1, and the material will become translucent.

    I know you have done that in your example, but you have a silver translucent object painted on a silver background, so you aren't going to see much. Also, .3 on opacity for certain colors will still be pretty opaque, so you might not see much through it.   As noted in:

    There's no depth sort algorithm though, meaning that order of how 3D shapes are added to the scene matters.

    So, if we take the 3D orbiter example from here:

    And modify the group order from:

    Group space = new Group(sun, sunsRadiance, orbit, earth);
    

    to:

    Group space = new Group(earth, orbit, sun, sunsRadiance);
    

    And change the diffuseColor of the Sun to an opacity of .1.

    sun.setMaterial(
            new PhongMaterial(
                    Color.ORANGERED
                            .deriveColor(
                                    0,
                                    1,
                                    1,
                                    .1
                            ),
                    null,
                    null,
                    null,
                    illuminationMap
            )
    );
    

    Then you will see the earth brightly lit in daytime as it passes behind the translucent sun.

    front side back