cannon
Version:
A lightweight 3D physics engine written in JavaScript.
74 lines (59 loc) • 2.37 kB
HTML
<html>
<head>
<title>cannon.js - callbacks demo</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css" type="text/css"/>
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<script src="../build/cannon.js"></script>
<script src="../build/cannon.demo.js"></script>
<script src="../libs/dat.gui.js"></script>
<script src="../libs/Three.js"></script>
<script src="../libs/TrackballControls.js"></script>
<script src="../libs/Detector.js"></script>
<script src="../libs/Stats.js"></script>
<script src="../libs/smoothie.js"></script>
<script>
/**
* A demo showing how to use the preStep callback to add a force to a body.
* This will act like a force field.
*/
var demo = new CANNON.Demo();
demo.addScene("Moon",function(){
var world = demo.getWorld();
var mass = 5;
var moonShape = new CANNON.Sphere(0.5);
var planetShape = new CANNON.Sphere(3.5);
var moon = new CANNON.Body({ mass: mass });
moon.addShape(moonShape);
var planet = new CANNON.Body({ mass: 0 });
planet.addShape(planetShape);
moon.position.set(5,0,0);
moon.velocity.set(0,0,8);
moon.linearDamping = 0.0;
// Use the preStep callback to apply the gravity force on the moon.
// This callback is evoked each timestep.
moon.preStep = function(){
// Get the vector pointing from the moon to the planet center
var moon_to_planet = new CANNON.Vec3();
this.position.negate(moon_to_planet);
// Get distance from planet to moon
var distance = moon_to_planet.norm();
// Now apply force on moon
// Fore is pointing in the moon-planet direction
moon_to_planet.normalize();
moon_to_planet.mult(1500/Math.pow(distance,2),this.force);
}
// We add the objects to the world to simulate them
world.add(moon);
world.add(planet);
// And we add them to the demo to make them visible
demo.addVisual(moon);
demo.addVisual(planet);
});
demo.start();
</script>
</body>
</html>