Get started with p2.js CDN

MIT licensed

P2.js: 2D web physics engine with collision detection, rigid body dynamics.

Tags:
  • p2.js
  • p2
  • physics
  • engine
  • 2d

Stable version

Copied!

How to start using p2.js CDN


<!DOCTYPE html>
<html>
<head>
    <title>Get started with p2.js CDN - cdnhub.io</title>
    <script src="https://cdn.cdnhub.io/p2.js/0.7.1/p2.min.js"></script>
    <style>
        #canvas { width: 800px; height: 600px; border: 1px solid black; }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        const canvas = document.getElementById('canvas');
        const context = canvas.getContext('2d');
        const world = new p2.World({
            gravity: [0, 10]
        });

        const groundBody = new p2.Body({ mass: 1, position: [0, canvas.height - 20] });
        groundBody.isStatic = true;
        groundBody.shape = new p2.Box({ width: canvas.width, height: 20 });
        world.add(groundBody);

        const ball = new p2.Body({ mass: 1, position: [50, 50] });
        ball.shape = new p2.Circle({ radius: 10 });
        world.add(ball);

        function draw() {
            context.clearRect(0, 0, canvas.width, canvas.height);
            world.step();
            world.bodies.forEach(body => {
                if (body.shape) {
                    context.beginPath();
                    body.shape.render(context, { x: body.position.x, y: body.position.y });
                    context.fillStyle = body.position.x > 400 ? 'red' : 'blue';
                    context.fill();
                }
            });
            requestAnimationFrame(draw);
        }

        draw();
    </script>
</body>
</html>
Copied!
Copied!
Copied!
Copied!

All versions