Dynamic reflections in Three.js
A simple introduction to Three.js CubeCamera
A few months ago I wrote a post where I explained how to add reflections to objects in Three.js. The approach described in that post is ok, but those reflections are faked, what if you want real time reflections on your objects?
Here you can see an example of dynamic reflections. Notice how the rings reflex on the sphere is drawn in real time.
This is another example (real-time version here) of real-time reflections in a more complex scene.
These examples are on spheres but you can apply the same technique to every other geometry.
Real-time reflections can really improve the aesthetic of your work, even though they are computationally heavy.
It is easy to add this type of reflections to your scene, you only have to use the CubeCamera object shipped with Three.js.
As the description says, this objects creates 6 cameras that render on a render target cube. You don’t really need to know what a render target cube is, what you need to know is that the CubeCamera will render the images on a texture, that you can use as a cube map on your objects in order to add reflections.
First of all create your CubeCamera and add it to the scene.
const cubeCamera = new THREE.CubeCamera(near, far, resolution);
scene.add(cubeCamera);
Near and far are used to define how close and how far the camera is able to see. (Objects with a distance from the camera smaller or greater than near and far respectively won’t be rendered).
Resolution basically defines the resolution of the image. The higher the resolution the heavier the rendering will be, so don’t abuse it. I usually go with 512.
Remember to update the CubeCamera at each frame.
cubeCamera.updateCubeMap(renderer, scene);
At this point you only need to take the texture and apply it to your material as an environment map.
material.envMap = cubeCamera.renderTarget.texture;
Obviously you can play with the material’s properties in order to change the aesthetic of the reflections. If you’re feeling brave you can even do some post processing on it :)
You should also set the position of your CubeCamera, based on what do you want to see reflected on your object.
As the previous technique with a static texture, this one is straightforward to implement yet graphically extremely effective.
Where can you find me?
Follow me on Twitter: https://twitter.com/psoffritti
My website/portfolio: pierfrancescosoffritti.com
My GitHub account: https://github.com/PierfrancescoSoffritti
My LinkedIn account: linkedin.com/in/pierfrancescosoffritti/en