Top Related Projects
A lightweight 3D physics engine written in JavaScript.
Lightweight 3d physics engine for javascript
Direct port of the Bullet physics engine to JavaScript using Emscripten
Physics plugin for Three.js
a 2D rigid body physics engine for the web ▲● ■
Quick Overview
Cannon-es is a lightweight 3D physics engine for the web, ported from the original cannon.js library to ES6 modules. It provides a simple and efficient way to add realistic physics simulations to web-based 3D applications, games, and visualizations.
Pros
- Lightweight and performant, optimized for web environments
- Easy integration with modern JavaScript frameworks and bundlers
- Supports various collision shapes and constraints
- Active community and ongoing development
Cons
- Limited documentation compared to some other physics engines
- May require additional setup for complex simulations
- Not as feature-rich as some larger physics engines
- Performance can degrade with a high number of objects
Code Examples
Creating a world and adding a sphere:
import { World, Body, Sphere } from 'cannon-es';
const world = new World();
world.gravity.set(0, -9.82, 0);
const radius = 1;
const sphereBody = new Body({
mass: 5,
shape: new Sphere(radius)
});
sphereBody.position.set(0, 10, 0);
world.addBody(sphereBody);
Applying forces to a body:
import { Vec3 } from 'cannon-es';
const force = new Vec3(100, 0, 0);
const point = new Vec3(0, 0, 0);
sphereBody.applyForce(force, point);
Collision detection:
world.addEventListener('collide', (event) => {
const { body, target } = event;
console.log(`Collision between ${body.id} and ${target.id}`);
});
Getting Started
To use cannon-es in your project:
-
Install the package:
npm install cannon-es
-
Import and use in your JavaScript file:
import { World, Body, Sphere } from 'cannon-es'; const world = new World(); world.gravity.set(0, -9.82, 0); // Create and add bodies to the world function animate() { world.step(1/60); // Update your 3D scene here requestAnimationFrame(animate); } animate();
Remember to integrate with your preferred 3D rendering library (e.g., Three.js) for visualization.
Competitor Comparisons
A lightweight 3D physics engine written in JavaScript.
Pros of cannon.js
- Established and well-known physics engine with a longer history
- Larger community and more existing resources for learning and troubleshooting
- More comprehensive documentation and examples
Cons of cannon.js
- No longer actively maintained, with the last update in 2016
- Uses older JavaScript syntax and module system
- May have performance limitations compared to more modern implementations
Code Comparison
cannon.js:
var world = new CANNON.World();
world.gravity.set(0, -9.82, 0);
var shape = new CANNON.Box(new CANNON.Vec3(1, 1, 1));
var body = new CANNON.Body({ mass: 1 });
body.addShape(shape);
world.addBody(body);
cannon-es:
import { World, Box, Body, Vec3 } from 'cannon-es';
const world = new World();
world.gravity.set(0, -9.82, 0);
const shape = new Box(new Vec3(1, 1, 1));
const body = new Body({ mass: 1 });
body.addShape(shape);
world.addBody(body);
The code structure is similar, but cannon-es uses ES6 module imports and more modern JavaScript syntax. cannon-es is essentially a maintained fork of cannon.js, offering improved performance, bug fixes, and better compatibility with modern JavaScript ecosystems while maintaining a similar API.
Lightweight 3d physics engine for javascript
Pros of Oimo.js
- Lighter weight and potentially faster for simple physics simulations
- Easier to integrate with existing JavaScript projects
- More straightforward API for basic physics operations
Cons of Oimo.js
- Less actively maintained compared to cannon-es
- Fewer advanced features and constraints
- Limited documentation and community support
Code Comparison
Oimo.js:
var world = new OIMO.World({
timestep: 1/60,
iterations: 8,
broadphase: 2,
worldscale: 1,
random: true
});
cannon-es:
const world = new CANNON.World({
gravity: new CANNON.Vec3(0, -9.82, 0),
allowSleep: true
});
Both libraries offer similar basic functionality for creating physics worlds, but cannon-es provides more options for fine-tuning the simulation parameters. Oimo.js has a more compact syntax for world creation, while cannon-es offers more explicit control over gravity and sleep states.
Oimo.js is better suited for simpler physics simulations in JavaScript environments, while cannon-es provides a more robust and feature-rich physics engine with better long-term support and development. The choice between the two depends on the specific requirements of your project, with cannon-es being the preferred option for more complex and demanding physics simulations.
Direct port of the Bullet physics engine to JavaScript using Emscripten
Pros of Ammo.js
- More mature and widely adopted in the industry
- Offers a broader range of physics simulations and features
- Better performance for complex simulations due to its C++ core
Cons of Ammo.js
- Larger file size and potentially slower initial load times
- Steeper learning curve due to its complexity and C++ origins
- Less idiomatic JavaScript API, which may feel less natural for web developers
Code Comparison
Ammo.js:
var transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(0, 10, 0));
var motionState = new Ammo.btDefaultMotionState(transform);
var shape = new Ammo.btSphereShape(0.5);
Cannon-es:
const sphereShape = new CANNON.Sphere(0.5);
const sphereBody = new CANNON.Body({
mass: 5,
shape: sphereShape,
position: new CANNON.Vec3(0, 10, 0)
});
Cannon-es provides a more straightforward and JavaScript-friendly API, making it easier for web developers to work with physics simulations. However, Ammo.js offers more advanced features and potentially better performance for complex scenarios, at the cost of a steeper learning curve and larger file size.
Physics plugin for Three.js
Pros of Physijs
- Tighter integration with Three.js, making it easier to use for developers already familiar with Three.js
- Simpler API for basic physics simulations, requiring less setup code
- Built-in support for common physics objects like planes, spheres, and boxes
Cons of Physijs
- Less actively maintained, with the last update in 2017
- Limited to browser environments, as it relies on Web Workers
- Fewer advanced features and customization options compared to cannon-es
Code Comparison
Physijs:
var scene = new Physijs.Scene();
var box = new Physijs.BoxMesh(
new THREE.BoxGeometry(5, 5, 5),
new THREE.MeshBasicMaterial({ color: 0xff0000 })
);
scene.add(box);
cannon-es:
const world = new CANNON.World();
const boxShape = new CANNON.Box(new CANNON.Vec3(2.5, 2.5, 2.5));
const boxBody = new CANNON.Body({ mass: 1, shape: boxShape });
world.addBody(boxBody);
Both libraries provide physics simulation capabilities for web-based 3D applications, but cannon-es offers more flexibility and active development. Physijs is more tightly integrated with Three.js, while cannon-es requires additional setup but provides more advanced features and better performance.
a 2D rigid body physics engine for the web ▲● ■
Pros of matter-js
- More comprehensive documentation and examples
- Broader feature set, including constraints and composites
- Easier to use for beginners due to simpler API
Cons of matter-js
- Generally slower performance, especially for complex simulations
- Less accurate for certain types of physics simulations
- Larger file size, which may impact load times for web applications
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);
cannon-es:
const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);
const shape = new CANNON.Box(new CANNON.Vec3(1, 1, 1));
const body = new CANNON.Body({ mass: 1 });
body.addShape(shape);
world.addBody(body);
matter-js provides a more abstracted API, making it easier for beginners to get started. cannon-es offers more granular control over physics properties and is generally more performant for complex simulations. matter-js includes built-in rendering capabilities, while cannon-es typically requires integration with a separate rendering library like Three.js.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
cannon-es
This is a maintained fork of cannon.js, originally created by Stefan Hedman @schteppe.
It's a type-safe flatbundle (esm and cjs) which allows for tree shaking and usage in modern environments.
These minor changes and improvements were also made:
- These PRs from the original repo were merged: schteppe/cannon.js#433, schteppe/cannon.js#430, schteppe/cannon.js#418, schteppe/cannon.js#360, schteppe/cannon.js#265, schteppe/cannon.js#392, schteppe/cannon.js#424
- The
ConvexPolyhedron
constructor now accepts an object instead of a list of arguments. #6 - The
Cylinder
is now oriented on the Y axis. #30 - The
type
property of theCylinder
is now equal toShape.types.CYLINDER
. #59 Body.applyImpulse()
andBody.applyForce()
are now relative to the center of the body instead of the center of the world 86b0444- Sleeping bodies now wake up if a force or an impulse is applied to them #61
- Added a property
World.hasActiveBodies: boolean
which will be false when all physics bodies are sleeping. This allows for invalidating frames when physics aren't active for increased performance. - Add support for Trigger bodies. #83
- Deprecated properties and methods have been removed.
- The original cannon.js debugger, which shows the wireframes of each body, has been moved to its own repo cannon-es-debugger.
- Added optional property
World.frictionGravity: Vec3
which can be set to customize the force used when computing the friction between two colliding bodies. Ifundefined
,World.gravity
will be used. This property is useful to enable friction in zero gravity. This addresses issue #224 and follows the pattern established for p2.js.
If instead you're using three.js in a React environment with react-three-fiber, check out use-cannon! It's a wrapper around cannon-es.
Installation
yarn add cannon-es
Usage
import { World } from 'cannon-es'
// ...
or, if you're using webpack, you can import it like this while still taking advantage of tree shaking:
import * as CANNON from 'cannon-es'
// ...
Documentation
Examples
TO DO:
- Fix Octree
as any
assertions, and removeas any
type assertions wherever possible - Remove use of defined assertion (!) where possible (profile performance to ensure no degradation)
- Convert to abstract classes where possible (Equation, Solver, etc.?)
- V-HACD support (https://github.com/pmndrs/use-cannon/issues/35#issuecomment-600188994)
- Explore performance enhancements:
Top Related Projects
A lightweight 3D physics engine written in JavaScript.
Lightweight 3d physics engine for javascript
Direct port of the Bullet physics engine to JavaScript using Emscripten
Physics plugin for Three.js
a 2D rigid body physics engine for the web ▲● ■
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot