Skip to content

Change Mass

Working Example

<>

Description

All the Cannon Boxes created in this example are initialized with a mass of 0. This means that they will be static objects in the scene. They will not be affected by gravity or can be pushed around due to any collisions from other boxes.

When clicking a box, its mass is updated to 1. The box will now be affected by gravity and will fall freely. It may also collide with other boxes as it falls.

As each Cannon Box is created, a reference to its API is also created which means that we can then dynamically modify its properties in the Cannon world at runtime.

E.g., When a Box is clicked, its mass is updated to 1

function Box(props) {
  const [ref, api] = useBox(
    () => ({ args: [1, 1, 1], mass: 0, type: 'Dynamic', ...props }),
    useRef()
  )

  return (
    <mesh
      ref={ref}
      onPointerDown={(e) => {
        e.stopPropagation()
        api.mass.set(1)
      }}
    >
      <boxGeometry args={[1, 1, 1]} />
      <meshNormalMaterial />
    </mesh>
  )
}

Note that modifying the Gravity sliders in the Leva GUI will have no effect on the static boxes with mass 0. But will affect any boxes that have been clicked and had there mass updated to a number higher than 0.

Change Mass (Working Example) sbedit.net

GitHub Branch

git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout changeMass
npm install
npm start

Comments