Get started with planck-js CDN

Zlib licensed

Planck-js is a open-source 2D physics engine for the web written in JS.

Tags:
  • box2d
  • html5
  • javascript
  • game
  • physics
  • engine
  • 2d
  • mobile

Stable version

Copied!

How to start using planck-js CDN


<!DOCTYPE html>
<html>
<head>
  <title>Get started with planck-js CDN - cdnhub.io</title>
  <style>
    #gameCanvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <canvas id="gameCanvas" width="800" height="600"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/planck-js@0.2.7/build/planck.min.js"></script>
  <script>
    const canvas = document.getElementById('gameCanvas');
    const context = canvas.getContext('2d');
    const width = canvas.width;
    const height = canvas.height;

    const engine = new p5.Vector();
    const world = new p5.World();

    world.gravity.set(0, 10);

    const groundBody = new p5.Body();
    groundBody.position.set(width / 2, height);
    groundBody.isStatic = true;
    groundBody.shape = new p5.Box(groundBody, 100, 20);
    world.addBody(groundBody);

    const playerBody = new p5.Body();
    playerBody.position.set(width / 2, height / 2);
    playerBody.mass = 50;
    playerBody.shape = new p5.Box(playerBody, 20, 20);
    world.addBody(playerBody);

    const playerForce = new p5.Vector();

    function setup() {
      canvas.width = width;
      canvas.height = height;
      world.setBounds(0, 0, width, height);
    }

    function draw() {
      context.clearRect(0, 0, width, height);
      world.update();

      context.fillStyle = 'gray';
      groundBody.shape.show(context);

      context.fillStyle = 'red';
      playerBody.shape.show(context);

      context.fillStyle = 'white';
      context.fillText('Press arrow keys to move', 10, 30);

      if (keyIsDown(LEFT_ARROW)) {
        playerForce.x -= 5;
      }
      if (keyIsDown(RIGHT_ARROW)) {
        playerForce.x += 5;
      }
      if (keyIsDown(UP_ARROW)) {
        playerForce.y -= 5;
      }
      if (keyIsDown(DOWN_ARROW)) {
        playerForce.y += 5;
      }

      playerBody.applyForce(playerForce);
      playerForce.set(0, 0);

      context.save();
      context.translate(playerBody.position.x, playerBody.position.y);
      context.rotate(playerBody.angle);
      context.fillStyle = 'white';
      context.fillRect(-10, -10, 20, 20);
      context.restore();
    }

    document.addEventListener('keydown', function() {
      if (keyCode === LEFT_ARROW || keyCode === RIGHT_ARROW || keyCode === UP_ARROW || keyCode === DOWN_ARROW) {
        playerForce.add(keyCodeX[keyCode]);
      }
    });
  </script>
</body>
</html>
Copied!
Copied!
Copied!
Copied!

All versions