Cannon.js is an open sourceJavaScript3Dphysics 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, convex polyhedron, particle, and heightfield. This collection of shapes matches the collection used by rendering engines such as Three.js and Babylon, but is not complete. For example, it is not sufficient for X3DOM,[4] an application of X3D which allows 3D graphics to be included in web pages without the need for a plug-in.[5]
Cannon.js can be used with Three.js and Babylon.js[8][9] WebGL renderers to generate physics-based 3D scenes. It can also be used to provide networked-physics synchronization for multiplayer online games using Lance.gg[10]
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 worldvarworld=newCANNON.World();world.gravity.set(0,0,-9.82);// m/s²// Create a spherevarradius=1;// mvarsphereBody=newCANNON.Body({mass:5,// kgposition:newCANNON.Vec3(0,0,10),// mshape:newCANNON.Sphere(radius)});world.addBody(sphereBody);// Create a planevargroundBody=newCANNON.Body({mass:0// mass == 0 makes the body static});vargroundShape=newCANNON.Plane();groundBody.addShape(groundShape);world.addBody(groundBody);varfixedTimeStep=1.0/60.0;// secondsvarmaxSubSteps=3;// Start the simulation loopvarlastTime;(functionsimloop(time){requestAnimationFrame(simloop);if(lastTime!==undefined){vardt=(time-lastTime)/1000;world.step(fixedTimeStep,dt,maxSubSteps);}console.log("Sphere z position: "+sphereBody.position.z);lastTime=time;})();
^ abHuber, Linda (2013). "Initial Steps for the Coupling of JavaScript Physics Engines with X3DOM". In Jan Bender; Jeremie Dequidt; Christian Duriez; Gabriel Zachmann (eds.). Workshop on Virtual Reality Interaction and Physical Simulation (VRIPHYS 2013). The Eurographics Association. pp. 81–90. doi:10.2312/PE.vriphys.vriphys13.081-090. ISBN978-3-905674-57-6. {{cite book}}: |journal= ignored (help)