...

/

Add and Remove Objects and Fog

Add and Remove Objects and Fog

Learn to create, add, and remove new objects to the Three.js scene.

Adding and removing objects 

With these ControlsControls, we can add cubes to the scene and remove the cube that was last added. It also allows us to change the background of the scene and set the material and the environment map for all the objects in the scene. We’ll explore these various options and how we can use them to configure a THREE.Scene. We’ll start by looking at how we can add and remove THREE.Mesh objects to and from a scene. The following code shows the function we call when we click on the “addCube” button: 

Press + to interact
const addCube = (scene) => {
const color = randomColor();
const pos = randomVector({
xRange: { fromX: -4, toX: 4 },
yRange: { fromY: -3, toY: 3 },
zRange: { fromZ: -4, toZ: 4 },
});
const rotation = randomVector({
xRange: { fromX: 0, toX: Math.PI * 2 },
yRange: { fromY: 0, toY: Math.PI * 2 },
zRange: { fromZ: 0, toZ: Math.PI * 2 },
});
const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const cubeMaterial = new THREE.MeshStandardMaterial({
color: color,
roughness: 0.1,
metalness: 0.9,
});
const cube = new THREE.Mesh(geometry, cubeMaterial);
cube.position.copy(pos);
cube.rotation.setFromVector3(rotation);
cube.castShadow = true;
scene.add(cube);
};

Let us understand the preceding code in detail: 

  • Lines 2–12: First, we have determined some random settings for the cube that will be added: a random color (by calling the randomColor() helper function), a random position, and a random rotation. These last two are randomly generated by calling randomVector()

  • Lines 13–22: Next, we create the geometry we want to add to the scene: a cube. We just create a new THREE.BoxGeometry for this, define a material (THREE.MeshStandardMaterial in this example), and combine these two into THREE.Mesh. We use random variables to set the cube’s position and rotation.  ...