With Three JS 3D Reflections?

Is there a way to create a js snippet for adding reflections to 3d models via three.js? I’ve seen videos about it and three.js does indeed support cubemaps. I’m trying to make the player vehicle reflective. I’ve tried writing one myself although im not very fluent in js and I don’t know where to go from here:

const player = runtimeScene.getObjects("Player");
const cubeCamera = new THREE.CubeCamera(1, 1000, 512); 
scene.add(cubeCamera);
cubeCamera.updateCubeMap(renderer, scene);
cubeCamera.update( renderer, scene );
renderer.render( scene, camera );

Any ideas and help appreciated! :grinning:

Hi.
The cubeCamera will render 6 directions of reflections for us, as long as we give it something to render it onto.
So first make it a renderTarget.

renderTarget = new THREE.WebGLCubeRenderTarget( size, 
{
	format: THREE.RGBAFormat,
	generateMipmaps: true,
	minFilter: THREE.LinearMipmapLinearFilter
});
renderTarget.texture.type = THREE.HalfFloatType;

Then when you instance the cubeCamera, give it the renderTarget.

const cubeCamera = new THREE.CubeCamera(near, far, renderTarget);

The rendered cubemap is stored at .texture. You can apply it to the material like this.

mesh.material.envMap = renderTarget.texture;

Lastly, for realtime reflections of moving objects, it will have to be updated every frame in your render loop.

render()
{
  cubeCamera.position.copy(reflectingObject.position); // properly position the cubeCamera
  reflectiveObject.visible = false; // dont want to self reflect its insides
  cubeCamera.update(renderer,scene); //render the reflection
  reflectiveObject.visible = true; // dont forget to turn the object back on for normal rendering
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}

I would only update the cubeCamera when something in the scene has moved.

1 Like

Thanks for the advice! I think im close to getting it however I’d like to ask how to get the newly created cube camera in an “always” loop? so theres this code that instances the cube camera and configures it:

and ive made a second gdevelop function to run it when vehicle’s speed isn’t 0:

However I can’t really call cubeCamera.position etc because I haven’t referenced it before as
const cubeCamera = …
I’d love to somehow get it to use in this function just like the reflective object with the name id, perhaps I could get it via

const cubeCamera = gdjs.__WithThreeJS.get("cubeCamera");

?

Also idk if it will conflict somehow but i’ve got a second third person camera for the player vehicle and there’s this code thats running on scene post events (every frame):

I was wondering if any of the camera/render stuff might be conflicting with this in the future?