Cannon.js
Developer(s) | Stefan Hedman |
---|---|
Stable release | 0.6.2
/ March 28, 2015[1] |
Repository | |
Written in | JavaScript |
Operating system | OS independent |
Type | 3D physics engine |
License | MIT License |
Website | www |
Cannon.js is an open source JavaScript 3D physics engine created by Stefan "schteppe" Hedman.[2] Unlike physics engine libraries ported from C++ to JavaScript, cannon.js is written in JavaScript from the start and can take advantage of its features.[3] In a 2013 comparison with Ammo.js, cannon.js was found to be "more compact, more comprehensible, more powerful with regard to its performance and also easier to understand", but did not have as many features.[4]
Features
Cannon.js supports the following shapes: sphere, plane, box, cylinder,
The physics engine implements rigid-body dynamics, discrete
Cannon.js can be used with Three.js and Babylon.js
Example
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.).[11]
// 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;
})();
References
- ^ "Releases · schteppe/cannon.js". GitHub.com. Retrieved 11 May 2021.
- ^ "Stefan Hedman". GitHub. Retrieved 27 April 2017.
- ^ Prall, Chandler (10 April 2012). "JavaScript Physics Engines Comparison". Build New Games. Retrieved 27 April 2017.
- ^ )
- ^ "Background: What is X3DOM, and what can it do for me?". official x3dom documentation. x3dom.org. Retrieved 27 April 2017.
- ^ "Branch: master. cannon.js/README.markdown". GitHub. 22 April 2015. Retrieved 27 April 2017.
- ^ "Cloth physics simulation".
- ^ "Create wonderful interactive games for the web: Using webgl and a physics engine (babylon.js & cannon.js)". Retrieved 21 February 2017.
- ^ "MSDN Game Development with Babylon.js". Retrieved 21 February 2017.
- ^ "Lance source repository". GitHub.
- ^ "Cannon.js - JavaScripting". www.javascripting.com. Retrieved 2020-12-22.