How to remove the child of an Object3D in three.js

We can use two methods to remove the child of an Object3D class object which is present inside the three.js scene graph:

  • The remove() method

  • The removeFromParent() method

Syntax

The remove() method

This method is invoked through the parent object.

parentObject.remove(childObject);

Parameters

This method takes the Object3D to be removed as a parameter. Here,

  • parentObject: This is the parent whose child we want to remove.
  • childObject: This is the child that we want to remove.

Note: The childObject must already be a child of parentObject before it is removed. If it is not already a child, no effect takes place.

TheremoveFromParent() method

This method is invoked through the child itself.

childObject.removeFromParent();

Parameters

  • This method does not take any parameters.

  • childObject: This is the child who is to be removed from its parent.

Code example

We'll demonstrate the removal of a child with the help of an example:

Code explanation

In the code shown above, we create a scene in three.js. Here, shape_one is the square and is the parent of the two spheres. The green sphere is shape_two and the red one is shape_three.

  • Lines 47 & 48: We added shape_two and shape_three to shape_one as children.

The scene graph of the code shown above looks something like the illustration shown below:

Scene graph of the code shown above

Removing a child from the parent object will make the scene graph look the following illustration:

remove()
removeFromParent()

This will prevent shape_two from being rendered entirely as it is no longer a part of the scene.

Here,

  • Line 58: We remove shape_two from the children of shape_one using remove() and can observe that it is no longer a part of the scene.

  • Line 61: We can uncomment this line and comment Line 58 to observe the same effect of removeFromParent() method as well.

Copyright ©2024 Educative, Inc. All rights reserved