Andy Ray Andy Ray - 1 year ago 90
Javascript Question

three.js - drawing two overlapping transparent spheres and hiding intersection

I have two transparent, overlapping spheres in a webgl context. During overlap, I would like to control how the spheres are drawn. You can see my problem at this page:

When the red and blue sphere overlap, I would like for the blue sphere to be hidden behind the red sphere.

If I simply change the order in which the spheres are added to the scene (if I add the big sphere first), I get the desired behavior:

However, things are different in my project. I see the intersection even though I add the big sphere first.

The closest I have gotten is moving the smaller spheres closer to the camera. in this example, I have moved the smaller spheres 10 units closer:

However, if you move around with the arrow keys, you can see the intersection flash every now and then, and sometimes flat out rudely stay visible (especially with bubbles coming in from the side)

I have tried setting

depwthWrite: false
on both materials but that doesn't have any effect.

I have messed a bit with
renderer.sortObjects = false
but I think this is removing the "natural" draw order that I want to occur with the rest of the scene. It is just these spheres I am at issue with.

  1. Can I force the draw order of transparent objects in webgl / three.js? It seems like they are z-fighting even when moving the smaller spheres 10 units closer

  2. or is there any way to force the behavior of overlapping transparent objects?

Answer Source

After much head banging (not the good kind) I have discovered that you can force draw order with a flag on the mesh.

For Three r70 and above use renderOrder

mesh.renderOrder = 0.5; // Value from 0 to 1

For Three r69 and below use renderDepth

mesh.renderDepth = 0.5; // Value from 0 to 1

It draws lowest first, highest last.