Learning Three.js

or WebGL for Dummies

Live Cube Maps Reflections in Your Three.js Game With threex.cubecamera

This is post is part of the ‘one threex a day’ challenge. This challenge is to publish every day one game extension for three.js! One per day, every day and that for 2month! In this post, we gonna talk about threex.cubecamera. threex.cubecamera is a three.js games extension which provides a helper for cube cameras. It is very useful when a given object must reflect a texture cube live. Just look at it, you can see the reflection as clear as a real life mirror! You can give your texture the color you want, for example in the demo I created a “gold” sphere to give it a shinier look. Be careful though, this requires 6 renderings of the scene every time you update it. It becomes expensive fast.

To see the other posts about one threex a day and forget our moto! “A THREEx extension a day, gets your game on its way!”

Show Don’t Tell

How To Install It

You can install it via script tag

1
<script src='threex.cubecamera.js'></script>

Or you can install with bower, as you wish.

1
bower install threex.cubecamera

How To Use It

First you need to create a classic mesh, the one which gonna reflect the live texture cube. In this example, we gonna create sphere with the color ‘gold’ like this.

1
2
3
4
5
6
var geometry    = new THREE.SphereGeometry(0.5, 32, 16)
var material    = new THREE.MeshPhongMaterial({
    color   : 'gold'
})
var mesh    = new THREE.Mesh(geometry, material)
scene.add( mesh )

Now we needs to create the cube camera which gonna update the texture cube live. We do that like this.

1
2
var cubeCamera  = new THREEx.CubeCamera(mesh)
scene.add(cubeCamera.object3d)

Don’t forget to update it when needed (likely at every frame)

1
cubeCamera.update(renderer, scene)

Now that we got the textureCube, we set the mesh material to reflect this texture cube.

1
material.envMap = cubeCamera.textureCube

This is it! Now you got the live texture cube on your sphere :)

Comments