Convert Figma logo to code with AI

pmndrs logouse-cannon

👋💣 physics based hooks for @react-three/fiber

2,756
154
2,756
32

Top Related Projects

16,610

a 2D rigid body physics engine for the web ▲● ■

A lightweight 3D physics engine written in JavaScript.

3,047

Lightweight 3d physics engine for javascript

4,134

Direct port of the Bullet physics engine to JavaScript using Emscripten

Quick Overview

use-cannon is a React hook for the cannon.js physics engine, designed to simplify the integration of 3D physics simulations in React applications. It provides a declarative way to create and manage physics objects, making it easier to build interactive 3D experiences with realistic physics behavior.

Pros

  • Seamless integration with React and Three.js ecosystems
  • Simplified API for working with cannon.js physics engine
  • Optimized performance through worker threads
  • Automatic cleanup and disposal of physics objects

Cons

  • Limited documentation and examples for advanced use cases
  • Dependency on cannon.js, which may have performance limitations for complex simulations
  • Potential learning curve for developers unfamiliar with 3D physics concepts
  • May require additional setup for certain edge cases or custom physics behaviors

Code Examples

Creating a simple physics-enabled box:

import { Physics, useBox } from '@react-three/cannon'
import { Canvas } from '@react-three/fiber'

function PhysicsBox() {
  const [ref] = useBox(() => ({ mass: 1, position: [0, 5, 0] }))
  return <mesh ref={ref}><boxGeometry /></mesh>
}

function App() {
  return (
    <Canvas>
      <Physics>
        <PhysicsBox />
      </Physics>
    </Canvas>
  )
}

Adding a static ground plane:

import { usePlane } from '@react-three/cannon'

function Ground() {
  const [ref] = usePlane(() => ({ rotation: [-Math.PI / 2, 0, 0] }))
  return (
    <mesh ref={ref}>
      <planeGeometry args={[10, 10]} />
    </mesh>
  )
}

Creating a compound body:

import { useCompoundBody } from '@react-three/cannon'

function CompoundShape() {
  const [ref] = useCompoundBody(() => ({
    shapes: [
      { type: 'box', position: [0, 0, 0], rotation: [0, 0, 0], args: [1, 1, 1] },
      { type: 'sphere', position: [0, 1, 0], args: [0.5] }
    ],
    mass: 1,
    position: [0, 5, 0]
  }))
  
  return <group ref={ref}>
    <mesh><boxGeometry args={[1, 1, 1]} /></mesh>
    <mesh position={[0, 1, 0]}><sphereGeometry args={[0.5, 32, 32]} /></mesh>
  </group>
}

Getting Started

  1. Install the package:

    npm install @react-three/cannon
    
  2. Wrap your scene with the Physics component:

    import { Physics } from '@react-three/cannon'
    import { Canvas } from '@react-three/fiber'
    
    function App() {
      return (
        <Canvas>
          <Physics>
            {/* Your physics-enabled components here */}
          </Physics>
        </Canvas>
      )
    }
    
  3. Use the provided hooks (e.g., useBox, useSphere, usePlane) to create physics-enabled objects in your scene.

Competitor Comparisons

16,610

a 2D rigid body physics engine for the web ▲● ■

Pros of matter-js

  • Pure JavaScript physics engine, making it easier to integrate into various JavaScript projects
  • More comprehensive documentation and examples
  • Broader range of features, including cloth, soft bodies, and constraints

Cons of matter-js

  • Generally slower performance compared to use-cannon
  • Steeper learning curve due to more complex API
  • Less optimized for React and Three.js integration

Code Comparison

matter-js:

var engine = Matter.Engine.create();
var world = engine.world;
var box = Matter.Bodies.rectangle(200, 200, 80, 80);
Matter.World.add(world, box);
Matter.Engine.run(engine);

use-cannon:

const [ref] = useBox(() => ({
  mass: 1,
  position: [0, 5, 0],
}));
return <mesh ref={ref}>{/* Mesh contents */}</mesh>;

Summary

matter-js is a versatile pure JavaScript physics engine with extensive features and documentation. It's suitable for various JavaScript projects but may have performance limitations. use-cannon, on the other hand, is optimized for React and Three.js integration, offering better performance but with a more focused feature set. The choice between them depends on the specific project requirements and the developer's familiarity with React and Three.js.

A lightweight 3D physics engine written in JavaScript.

Pros of cannon.js

  • Standalone physics engine, usable in various JavaScript environments
  • More mature and established project with a longer history
  • Offers more direct control over the physics simulation

Cons of cannon.js

  • Requires more manual setup and integration with rendering libraries
  • Less optimized for React and Three.js ecosystems
  • May have a steeper learning curve for React developers

Code Comparison

cannon.js:

const world = new CANNON.World();
const sphereShape = new CANNON.Sphere(1);
const sphereBody = new CANNON.Body({
  mass: 5,
  shape: sphereShape
});
world.addBody(sphereBody);

use-cannon:

const [ref, api] = useBox(() => ({
  mass: 5,
  position: [0, 10, 0],
}));
return <mesh ref={ref}>
  <boxBufferGeometry />
  <meshStandardMaterial />
</mesh>

Summary

cannon.js is a versatile physics engine for JavaScript, while use-cannon is a React hooks-based wrapper for cannon.js, specifically designed for use with React and Three.js. use-cannon simplifies the integration of physics in React-based 3D applications, offering a more declarative approach. However, cannon.js provides more flexibility and can be used in a wider range of projects beyond the React ecosystem. The choice between the two depends on the specific requirements of your project and your preferred development approach.

3,047

Lightweight 3d physics engine for javascript

Pros of Oimo.js

  • Lightweight and fast physics engine
  • Supports both 2D and 3D physics simulations
  • Easy to integrate with Three.js and other WebGL libraries

Cons of Oimo.js

  • Less active development and community support
  • Limited documentation and examples
  • Fewer advanced features compared to use-cannon

Code Comparison

Oimo.js:

var world = new OIMO.World({ 
    timestep: 1/60, 
    iterations: 8, 
    broadphase: 2,
    worldscale: 1, 
    random: true
});

var body = world.add({
    type: 'sphere',
    size: [1],
    pos: [0, 10, 0],
    move: true
});

use-cannon:

const { Physics, useSphere } = useCanon();

function Scene() {
  return (
    <Physics>
      <Sphere position={[0, 10, 0]} />
    </Physics>
  );
}

function Sphere(props) {
  const [ref] = useSphere(() => ({ mass: 1, ...props }));
  return <mesh ref={ref} />;
}

Oimo.js provides a more traditional JavaScript API, while use-cannon integrates seamlessly with React and Three.js, offering a more declarative approach to physics simulations. use-cannon also provides hooks for easy integration with React components, making it more suitable for React-based projects.

4,134

Direct port of the Bullet physics engine to JavaScript using Emscripten

Pros of Ammo.js

  • More mature and widely adopted physics engine
  • Supports a broader range of physics simulations and features
  • Better performance for complex simulations with many objects

Cons of Ammo.js

  • Steeper learning curve and more complex API
  • Requires manual memory management
  • Less integration-friendly with modern JavaScript frameworks

Code Comparison

use-cannon:

const [ref] = useBox(() => ({
  mass: 1,
  position: [0, 5, 0],
}))

return <mesh ref={ref}>
  <boxGeometry />
  <meshStandardMaterial />
</mesh>

Ammo.js:

const shape = new Ammo.btBoxShape(new Ammo.btVector3(1, 1, 1))
const transform = new Ammo.btTransform()
transform.setIdentity()
transform.setOrigin(new Ammo.btVector3(0, 5, 0))
const body = new Ammo.btRigidBody(new Ammo.btRigidBodyConstructionInfo(1, motionState, shape))
physicsWorld.addRigidBody(body)

use-cannon provides a more React-friendly API with hooks and declarative syntax, while Ammo.js offers lower-level control but requires more boilerplate code. use-cannon abstracts away much of the complexity, making it easier to integrate physics into React applications, especially when used with Three.js. Ammo.js, being a direct port of Bullet Physics, provides more advanced features and better performance for complex simulations at the cost of increased complexity.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build Status Discord Shield

Imgur

Monorepo for cannon-es web worker packages.

PackageDescription
@react-three/cannonReact hooks for cannon-es. Use this in combination with react-three-fiber.
@pmndrs/cannon-worker-apiWeb worker api for cannon-es. Used by @react-three/cannon.
@react-three/cannon-examplesExamples for @react-three/cannon

use-cannon Documentation

Please see the @react-three/cannon README documentation and getting started guide for using the react hooks and jsx interface.

Demos

Check out all of our @react-three/cannon examples at https://cannon.pmnd.rs

The code for the examples lives in ./packages/react-three-cannon-examples