Add and Remove Objects and Fog
Learn to create, add, and remove new objects to the Three.js scene.
We'll cover the following...
Adding and removing objects
With these 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:
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 callingrandomVector().Lines 13–22: Next, we create the geometry we want to add to the scene: a cube. We just create a new
THREE.BoxGeometryfor this, define a material (THREE.MeshStandardMaterialin this example), and combine these two intoTHREE.Mesh. We use random variables to set the cube’s position and rotation. ...