p2s
Version:
A JavaScript 2D physics engine.
102 lines (79 loc) • 2.52 kB
HTML
<html lang="en">
<head>
<title>p2.js Canvas example</title>
<meta charset="utf-8">
<script src="../../build/p2.js"></script>
</head>
<body>
<!-- The canvas, where we draw stuff -->
<canvas width="600" height="400" id="myCanvas"></canvas>
<script>
var canvas, ctx, w, h,
world, circleBody, planeBody;
init();
requestAnimationFrame(animate);
function init(){
// Init canvas
canvas = document.getElementById("myCanvas");
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext("2d");
ctx.lineWidth = 0.05;
// Init p2.js
world = new p2.World();
// Add a circle
circleShape = new p2.Circle({ radius: 1 });
circleBody = new p2.Body({ mass:1, position:[0,3] });
circleBody.addShape(circleShape);
world.addBody(circleBody);
// Add a plane
planeShape = new p2.Plane();
planeBody = new p2.Body();
planeBody.addShape(planeShape);
world.addBody(planeBody);
}
function drawCircle(){
ctx.beginPath();
var x = circleBody.interpolatedPosition[0],
y = circleBody.interpolatedPosition[1],
radius = circleShape.radius;
ctx.arc(x,y,radius,0,2*Math.PI);
ctx.stroke();
}
function drawPlane(){
var y = planeBody.interpolatedPosition[1];
ctx.moveTo(-w, y);
ctx.lineTo( w, y);
ctx.stroke();
}
function render(){
// Clear the canvas
ctx.clearRect(0,0,w,h);
// Transform the canvas
// Note that we need to flip the y axis since Canvas pixel coordinates
// goes from top to bottom, while physics does the opposite.
ctx.save();
ctx.translate(w/2, h/2); // Translate to the center
ctx.scale(50, -50); // Zoom in and flip y axis
// Draw all bodies
drawCircle();
drawPlane();
// Restore transform
ctx.restore();
}
var lastTime, timeStep = 1 / 60, maxSubSteps = 5;
// Animation loop
function animate(time){
requestAnimationFrame(animate);
var dt = lastTime ? (time - lastTime) / 1000 : 0;
dt = Math.min(1 / 10, dt);
lastTime = time;
// Move physics bodies forward in time
world.step(timeStep, dt, maxSubSteps);
// Render scene
render();
}
</script>
</body>
</html>