How to Destroy a Body in Planck.js?

Planck.js, a JavaScript rewriting of the Box2D physics engine, provides a specific lifecycle management system for rigid bodies to maintain performance and simulation accuracy. To completely remove a body from the simulation physics world, developers must utilize the world.destroyBody() method. This article provides a quick overview of how this method works, why it is necessary, and the crucial cleanup steps required to prevent memory leaks and unexpected behavior in your application.

The DestroyBody Method

In Planck.js, you cannot simply delete a body object using JavaScript’s delete keyword or by setting its reference to null. Because the physics world actively tracks the body for collision detection and velocity updates, you must explicitly tell the world to untrack and deallocate it.

The syntax for removing a body is straightforward:

// Assuming 'world' is your planck.World instance 
// and 'body' is the planck.Body you want to remove

world.destroyBody(body);

What Happens Behind the Scenes?

When world.destroyBody() is invoked, the physics engine automatically handles several complex teardown tasks:

Crucial Best Practices

While the destroyBody method handles the heavy lifting within the physics simulation itself, there are two critical rules you must follow to avoid application crashes:

Never destroy a body during a physics step. > If you attempt to call world.destroyBody() inside a collision listener (like BeginContact or EndContact) or while world.step() is executing, the simulation will throw an error or crash. Always flag the body for destruction and call the method after the step has finished.

Nullify your own references. Calling destroyBody() removes the body from the physics world, but if your game loops or rendering objects still hold a reference to that body variable, JavaScript cannot garbage collect it. Always clear your own custom references after destruction.