xxxxxxxxxx
95
let engine;
let world;
let circles = [];
let ground;
function setup() {
createCanvas(800, 600);
engine = Matter.Engine.create();
world = engine.world;
Matter.Engine.run(engine);
//grund
ground = Matter.Bodies.rectangle(width / 2, height - 20, width, 40, { isStatic: true });
Matter.World.add(world, ground);
// Set up collision events
Matter.Events.on(engine, 'collisionStart', collisionEvent);
Matter.Events.on(engine, 'collisionEnd', collisionEndEvent);
}
function draw() {
background(220);
circles.forEach(circle => {
let pos = circle.position;
let radius = circle.circleRadius;
// Check circle - collided state
if (circle.collided) {
fill(255, 0, 0); // Red if collided
} else {
fill(0, 150,0); // Green if not collided
}
ellipse(pos.x, pos.y, radius * 2);
});
// Display ground
fill(100);
rectMode(CENTER);
rect(ground.position.x, ground.position.y, width, 40);
}
function mouseClicked() {
let radius = random(10, 50);
let circle = Matter.Bodies.circle(mouseX, mouseY, radius);
circle.collided = false; // track collision state
Matter.World.add(world, circle);
circles.push(circle);
}
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
}
});
}
}