Add and Remove Objects and Fog
Explore how to add and remove 3D mesh objects in a Three.js scene using functions like add, remove, and getObjectByName. Understand how to enhance scene realism by applying fog effects and adjusting their parameters, allowing you to create visually dynamic and immersive 3D environments.
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:
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. ...