yarn add use-cannon
Experimental React hooks for cannon. Use this in combination with react-three-fiber.
- Doesn't block the main thread, runs in a web worker
- Supports instancing out of the box
- Least amount of friction you'll ever experience with a physics rig ... 🙈
Demos
Ping pong: https://codesandbox.io/s/white-resonance-0mgum
Cube pushing spheres away: https://codesandbox.io/s/r3f-cannon-instanced-physics-devf8
Heap of cubes: https://codesandbox.io/s/r3f-cannon-instanced-physics-g1s88
How it works
- Get all the imports that you need.
import Physics useBox ... from 'use-cannon'
- Create a physics world.
<Physics>/* Physics related objects in here please */</Physics>
- Pick a shape that suits your objects contact surface, it could be a box, plane, sphere, etc. Give it a mass, too.
const ref api =
- Take your object, it could be a mesh, line, gltf, anything, and tie it to the reference you have just received. Et voilà, it will now be affected by gravity and other objects inside the physics world.
<mesh = = = />
- You can interact with it by using the api, which lets you apply positions, rotations, velocities, forces and impulses.
- You can use the body api to subscribe to properties to get updates on each frame.
const velocity =
Simple example
Let's make a cube falling onto a plane. You can play with a sandbox here.
import Canvas from 'react-three-fiber'import Physics usePlane useBox from 'use-cannon' { const ref = return <mesh => <planeBufferGeometry ="geometry" = /> </mesh> } { const ref = return <mesh => <boxBufferGeometry ="geometry" /> </mesh> } ReactDOM
Api
Exports
Returned api
Props
FAQ
Broadphases
- NaiveBroadphase is as simple as it gets. It considers every body to be a potential collider with every other body. This results in the maximum number of narrowphase checks.
- SAPBroadphase sorts bodies along an axis and then moves down that list finding pairs by looking at body size and position of the next bodies. Control what axis to sort along by setting the axisIndex property.
Types
- A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
- A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
- A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.