Angry Birds Physics

This project is more of an exploration on what we can do using Matter.js Physics library. My inspiration comes from the popular game “Angry Birds” where you need to slingshot a bird so that it destroys blocks placed on the other end of the screen.

Angry birds · abstraction

I wanted to see if we could re-create the physics using Matter.js and have found that it’s pretty convenient and easy.

Here’s my sketch:

On mouse click, it ejects a bird (circle) to the right in a projectile motion and lets it hit the cubes. The cubes fade away when the bird hits the cube. After multiple hits, it eventually gets removed from the world.

Here’s how the mouseClick event is captured:

function mouseClicked() {
  // reset bird position and apply force
  Body.setPosition(bird, { x: mouseX, y: mouseY });
  Body.setVelocity(bird, { x: 0, y: 0 }); // reset velocity
  let force = createVector(0.06, -0.04);
  Body.applyForce(bird, bird.position, force);
}

Horizontal and vertical forces are applied to the bird to create the projectile motion. Matter.js handles the rest.

Here’s how the collision event is captured:

// collision event
Events.on(engine, "collisionStart", function (event) {
  let pairs = event.pairs;
  pairs.forEach(function (pair) {
    if (
      (pair.bodyA === bird && cubes.find((c) => c.body === pair.bodyB)) ||
      (pair.bodyB === bird && cubes.find((c) => c.body === pair.bodyA))
    ) {
      // Reduce opacity of the cube on collision
      let cube = cubes.find(
        (c) => c.body === pair.bodyA || c.body === pair.bodyB
      );
      if (cube) {
        cube.opacity = Math.max(0, cube.opacity - 100);
      }
    }
  });
});

 

Leave a Reply

Your email address will not be published. Required fields are marked *