Coding assignment #10 – Pendulum

Concept:

Inspired by Einstein’s cradle and the vintage clock’s pendulum, I’ve tried to create a collision system using Matter.js. It involves randomly generated pendula that collide with each other as they fall down. The user has the ability to move the pendula up and down, left and right, to create more collisions using mouse drag.

View post on imgur.com

View post on imgur.com

 

Sketch:

Code Walkthrough:

Repo: https://editor.p5js.org/bdr/sketches/vq6UC-qLu

Mouse constraints: Create a mouse constraint for the user to interact with each pendulum up and down, left and right.

// add mouse interaction
    let mouse = Mouse.create(canvas.elt)
    mouseConstraint = MouseConstraint.create(engine,{
      mouse: mouse
    })
    // add the mouse constraint to the world
    World.add(engine.world,mouseConstraint)
    // add the engine
    Matter.Runner.run(engine)

 

newPendulum() function: Generate a new pendulum body with a random position, create a constraint to suspend the pendulum from a fixed point at the top, and add the pendulum body and its constraint to the world.

function newpendulum() {
    let { Bodies, World, Constraint } = Matter
    let pendulum;
    // create new pendulum
    pendulum = Bodies.circle(random(width),random(height/5)-height/5, 40)
    pendulum.color = "#f9cca5"
    pendulums.push(pendulum)
    pendulum.s = 40
    // add line constraint
    let constraint = Constraint.create({
        pointA: { x: width/2, y: 52 },
        bodyB: pendulum,
        length: random(height/2,height*3/4),
        stiffness: 0.1,
    })
    // push to the world
    constraints.push(constraint)
    World.add(engine.world,[pendulum,constraint])
}

draw(): Generate a new pendulum every 20 frames, up to a maximum of 20 pendulums.

// new pendulum every 20 frames, up to a max of 20
if(frameCount % 20==0 && pendulums.length < 20){
     newpendulum(frameCount)
}
Possible Improvements:
  • Add sound to the collisions to make it more realistic
  • Implement a 3D sphere instead of a 2D circle

Leave a Reply

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