A lightweight 3D physics engine written in JavaScript.
npm install @cocos/cannonhtml
`
$3
Install via npm for cocos creator:
usage : npm install @cocos/cannon --save。
$3
The sample code below creates a sphere on a plane, steps the simulation, and prints the sphere simulation to the console. Note that Cannon.js uses SI units (metre, kilogram, second, etc.).
`javascript
// Setup our world
var world = new CANNON.World();
world.gravity.set(0, 0, -9.82); // m/s²
// Create a sphere
var radius = 1; // m
var sphereBody = new CANNON.Body({
mass: 5, // kg
position: new CANNON.Vec3(0, 0, 10), // m
shape: new CANNON.Sphere(radius)
});
world.addBody(sphereBody);
// Create a plane
var groundBody = new CANNON.Body({
mass: 0 // mass == 0 makes the body static
});
var groundShape = new CANNON.Plane();
groundBody.addShape(groundShape);
world.addBody(groundBody);
var fixedTimeStep = 1.0 / 60.0; // seconds
var maxSubSteps = 3;
// Start the simulation loop
var lastTime;
(function simloop(time){
requestAnimationFrame(simloop);
if(lastTime !== undefined){
var dt = (time - lastTime) / 1000;
world.step(fixedTimeStep, dt, maxSubSteps);
}
console.log("Sphere z position: " + sphereBody.position.z);
lastTime = time;
})();
`
If you want to know how to use cannon.js with a rendering engine, for example Three.js, see the Examples.
$3
* Rigid body dynamics
* Discrete collision detection
* Contacts, friction and restitution
* Constraints
* PointToPoint (a.k.a. ball/socket joint)
* Distance
* Hinge (with optional motor)
* Lock
* ConeTwist
* Gauss-Seidel constraint solver and an island split algorithm
* Collision filters
* Body sleeping
* Experimental SPH / fluid support
* Various shapes and collision algorithms (see table below)
| | Sphere | Plane | Box | Convex | Particle | Heightfield | Trimesh |
| :-----------|:------:|:-----:|:---:|:------:|:--------:|:-----------:|:-------:|
| Sphere | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| Plane | - | - | Yes | Yes | Yes | - | Yes |
| Box | - | - | Yes | Yes | Yes | Yes | (todo) |
| Cylinder | - | - | Yes | Yes | Yes | Yes | (todo) |
| Convex | - | - | - | Yes | Yes | Yes | (todo) |
| Particle | - | - | - | - | - | (todo) | (todo) |
| Heightfield | - | - | - | - | - | - | (todo) |
| Trimesh | - | - | - | - | - | - | - |
$3
The simpler todos are marked with `@todo`` in the code. Github Issues can and should also be used for todos.