The game 3D-scene has many objects (background, asteroids, rockets):
private Background background;
private Asteroid[] asteroids = new Asteroid[NUMBER_ASTEROIDS];
private Rocket[] rockets = new Rocket[NUMBER_ROCKETS];
...
public void onDrawFrame(GL10 glUnused) {
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
...
background.draw();
for (Asteroid asteroid: asteroids) asteroid.draw(); // draw all asteroids
for (Rocket rocket: rockets) rocket.draw(); // draw all rockets
...
}
Objects of asteroids and rockets use alpha-blending:
public class IceAsteroid extends Object3D implements Asteroid {
...
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
... // draw an object with a texture
GLES20.glDisable(GLES20.GL_BLEND);
...
}
public class Rocket extends Object3D {
...
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
... // draw an object without a texture
GLES20.glDisable(GLES20.GL_BLEND);
...
}
In general, translucency works well for the 3D-scene except that when the rockets are behind the asteroids they (rockets) are not visible. It seems that at this moment the transparency of the asteroids does not work, although the background behind the asteroids is visible. Can anyone please suggest why the rockets are not visible behind the asteroids? Thanks in advance!
Note: I tried to do this:
background.draw();
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
for (Asteroid asteroid: asteroids) asteroid.draw(); // draw all asteroids
for (Rocket rocket: rockets) rocket.draw(); // draw all rockets
GLES20.glDisable(GLES20.GL_BLEND);
But this did not solve the problem.
Solution: On the Rabbid76 advice, I sorted all the translucent objects in order from the back to the front:
Comparator<Object3D> comparatorByZ = (objectA, objectB) -> {
Float z1 = objectA.getZ();
Float z2 = objectB.getZ();
return z1.compareTo(z2);
};
...
background.draw();
Collections.sort(transparentObjects, comparatorByZ);
for (Object3D object3D: transparentObjects) object3D.draw();
In my case, that was enough.