Having worked with React and Three.js, I was intrigued by the idea of a React approach to 3D web apps.
I am specifically interested in Three.js + cannon physics, so when I saw the react-three developer examples I was excited to learn more.
Looking through the various demo projects, I couldn't find an instance where a collection of objects (like a bunch of spheres) were being dynamically created/destroyed. I did find a demo where a fixed number of objects are created/destroyed.
In the scenario I was thinking of, a specific item could be removed based on some criteria (like a collision event), with the total amount of objects growing and shrinking over time.
With this in mind, I put together this example where a ball is created every second. When a ball collides with a wall, it is removed...
The balls are managed using the familar React component Array.map() method that iterates over a collection of ball objects. When a ball collides with a wall, its key is used to filter it from the ball array.
That's all you need to do. React Three takes care of removing the ball mesh from the scene and the ball body from the world.
To keep logic centralized, I recommend zustand, brought to you by the collective of open-source developers that brought us @react-three/fiber and @react-three/cannon.
codesandbox.io/s/managing-dynamic-react-three-cannon-bodies
Make sure you have Node.js installed.
git clone https://github.com/patrick-s-young/dynamic-three-cannon-example.git # or clone your own fork
cd dynamic-three-cannon-example
npm install
npm start
- @react-three/fiber - React renderer for three.js.
- @react-three/cannon - React hooks for cannon-es, a rigid body physics engine.
- zustand - state-management solution that uses simplified flux principles.
- @react-three/drei - Helper library for @react-three/fiber.
- Patrick Young - Patrick Young
This project is licensed under the MIT License - see the LICENSE file for details.