Skip to content

Dynamically creating/disposing of react-three-fiber meshes + physics

Notifications You must be signed in to change notification settings

patrick-s-young/dynamic-react-three-fiber-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Managing the dynamic adding and removing of React Three Fiber meshes and bodies

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...

dynamic-react-three-fiber_1080x703

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.

View In Sandbox

codesandbox.io/s/managing-dynamic-react-three-cannon-bodies

Running Locally

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

Built With

Authors

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Dynamically creating/disposing of react-three-fiber meshes + physics

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published