Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use reflection in three.js?

I want to have a reflecting cube surface in a WebGL page with Three.js. It should resemble a mobile phone display, which reflects some light, but it still has to be black.

like image 343
Applecow Avatar asked Jul 06 '12 15:07

Applecow


People also ask

Can three js do 2D?

The way that Three. js structures its rendering means that the learning curve won't be too steep. It organizes all of the renders you'll do, whether 3D or 2D, under a “Scene” container.


1 Answers

I have created an example of a reflecting cube (and also a reflective sphere) with detailed comments. The live version is at

http://stemkoski.github.com/Three.js/Reflection.html

with nicely formatted code at

https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Reflection.html

(This is part of a collection of tutorial examples at http://stemkoski.github.com/Three.js/)

The main points are:

  • add to your scene a second camera (a CubeCamera) positioned at the object whose surface should be reflective
  • create a material and set the environment map as the results of rendering from this second camera, e.g.

for example:

 var mirrorCubeMaterial = new THREE.MeshBasicMaterial( 
    { envMap: mirrorCubeCamera.renderTarget } );
  • in your render function, you have to render from all your cameras. Temporarily hide the object that is reflecting (so that it doesn't get in the way of the camera you are going to use), render from that camera, then unhide the reflective object.

for example:

mirrorCube.visible = false;
mirrorCubeCamera.updateCubeMap( renderer, scene );
mirrorCube.visible = true;

These code snippets are from the links I posted above; check them out!

like image 168
Stemkoski Avatar answered Oct 18 '22 05:10

Stemkoski