Collision handling – week 10

To be very honest, I missed a lecture and was just trying to figure out how to use the basics of matter.js. I know for my final, I probably want something to be detected like a collision so I just played around with the different features such as gravity, collisions, ground or body.

I started off with a very basic program that just had the ground and the circles wherever the user clicked the screen.

I then added some code to identify whenever there was a collision or when they are collided.

if (circle.collided) {
      fill(255, 0, 0); // Red if collided
    } else {
      fill(0, 150,0); // Green if not collided
    }
function collisionEvent(event) {
  let pairs = event.pairs;
  for (let i = 0; i < pairs.length; i++) {
    let bodyA = pairs[i].bodyA;
    let bodyB = pairs[i].bodyB;

    // Check for collisions involving circles
    if ((circles.includes(bodyA) || circles.includes(bodyB)) && !isGroundCollision(bodyA, bodyB)) {
      circles.forEach(circle => {
        if ((circle === bodyA || circle === bodyB) && circle.collided !== true) {
          circle.collided = true; // true for collisions 
        }
      });
    }
  }
}

function isGroundCollision(bodyA, bodyB) {
  return (bodyA === ground || bodyB === ground);
}


function collisionEndEvent(event) {
  let pairs = event.pairs;
  for (let i = 0; i < pairs.length; i++) {
    let bodyA = pairs[i].bodyA;
    let bodyB = pairs[i].bodyB;

    // Find collided bodies and reset their state
    circles.forEach(circle => {
      if (circle === bodyA || circle === bodyB) {
        circle.collided = false; // Reset collided state to false
      }
    });
  }
}

The code above is to show if the circles are touching as before, the ball touching the ground would be considered a collision which I did not want. I needed the code to also traceback and see if the circles don’t touch anymore, and if they do not touch anymore, the ball should be green again.

This was my final code.

 

 

Leave a Reply

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