UNPKG

cannon

Version:

A lightweight 3D physics engine written in JavaScript.

180 lines (141 loc) 6.66 kB
<!DOCTYPE html> <html> <head> <title>SceneJS / cannon.js example</title> <meta charset="utf-8"> <style> * {margin:0;padding:0} </style> </head> <body> <script src="../libs/scenejs.js"></script> <script src="../build/cannon.js"></script> <canvas id="theCanvas" width="600" height="400"/> <script> var scene, quaternionNode, translationNode, world, body, shape, timeStep=1/60; initCannon(); initSceneJS(); animate(); function initCannon() { world = new CANNON.World(); world.gravity.set(0,0,0); shape = new CANNON.Box(new CANNON.Vec3(1,1,1)); body = new CANNON.Body({ mass: 1 }); body.addShape(shape); body.angularVelocity.set(0,10,0); body.angularDamping = 0.01; world.add(body); } function initSceneJS() { SceneJS.createScene({ id: "theScene", canvasId: "theCanvas", nodes: [ { type: "lookAt", eye : { x: 0.0, y: 10.0, z: 15 }, look : { y:1.0 }, up : { y: 1.0 }, nodes: [ { type: "camera", optics: { type: "perspective", fovy : 25.0, aspect : 1.47, near : 0.10, far : 300.0 }, nodes: [ { type: "renderer", clearColor: { r: 1.0, g: 1.0, b: 1.0 }, clear: { depth : true, color : true }, nodes: [ { type: "light", mode: "dir", color: { r: 1.0, g: 1.0, b: 1.0 }, diffuse: true, specular: true, dir: { x: 1.0, y: -0.5, z: -1.0 } }, { type: "light", mode: "dir", color: { r: 1.0, g: 1.0, b: 0.8 }, diffuse: true, specular: false, dir: { x: 0.0, y: -0.5, z: -1.0 } }, { type: "translate", id: "translate", x : 0.0, y : 0.0, z : 0.0, nodes: [ { type: "quaternion", id: "quaternion", x : 1.0, y : 0.0, z : 0.0, angle : 0.0, nodes: [ { type: "material", emit: 0, baseColor: { r: 0.5, g: 0.5, b: 0.6 }, specularColor: { r: 0.9, g: 0.9, b: 0.9 }, specular: 1.0, shine: 70.0, nodes: [ { type : "cube", xSize: shape.halfExtents.x, ySize: shape.halfExtents.y, zSize: shape.halfExtents.z, } ] } ] } ] } ] } ] } ] } ] }); // Get handles to some nodes scene = SceneJS.scene("theScene"); quaternionNode = scene.findNode("quaternion"); translationNode = scene.findNode("translate"); } function animate() { // Start the scene rendering scene.start({ idleFunc: updatePhysics }); } function updatePhysics() { var axisAndAngle, axis, angle; // Step the physics world world.step(timeStep); // Copy position from cannon to SceneJS translation node translationNode.set("xyz",body.position); // Get orientation of the body from cannon.js axisAndAngle = body.quaternion.toAxisAngle(); axis = axisAndAngle[0]; angle = axisAndAngle[1]; // Copy orientation to the SceneJS quaternion node quaternionNode.set("rotation",{ x: axis.x, y: axis.y, z: axis.z, angle: angle*180 / Math.PI }); } </script> </body> </html>