xxxxxxxxxx
93
let engine;
let world;
let circles = [];
let ground;
function setup() {
createCanvas(500, 650);
// Matter.js engine setup
engine = Matter.Engine.create();
world = engine.world;
// Create a ground
ground = Matter.Bodies.rectangle(width / 2, height - 10, width, 20, {
isStatic: true,
});
Matter.World.add(world, ground);
// Add some circles in a square configuration from the center
const numRows = 7;
const numCols = 7;
const circleSize = 20;
const spacing = 1;
const startX = width / 2 - ((numCols - 1) * spacing) / 2;
const startY = height / 2 - ((numRows - 1) * spacing) / 3;
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < numCols; j++) {
let x = startX + j * spacing;
let y = startY + i * spacing;
let circle = Matter.Bodies.circle(x, y, circleSize, { label: "Circle" });
Matter.World.add(world, circle);
circles.push(circle);
}
}
// Register collision event
Matter.Events.on(engine, "collisionStart", handleCollision);
}
function draw() {
background(0);
// Update the Matter.js engine
Matter.Engine.update(engine);
// Draw the ground
fill(127);
noStroke();
rectMode(CENTER);
rect(ground.position.x, ground.position.y, width, 20);
// Draw the circles
fill(0, 150, 255);
for (let circle of circles) {
push();
translate(circle.position.x, circle.position.y);
if (circle.colorChanging) {
fill(random(255), random(255), random(255));
circle.colorChanging = false; // reset the flag
}
ellipse(0, 0, circle.circleRadius * 2);
pop();
}
}
function mousePressed() {
// Apply a random force to each circle when the mouse is pressed
for (let circle of circles) {
let force = Matter.Vector.create(random(-0.05, 0.05), random(-0.1, 0));
Matter.Body.applyForce(circle, circle.position, force);
}
}
// Collision event handler function
function handleCollision(event) {
let pairs = event.pairs;
for (let i = 0; i < pairs.length; i++) {
let pair = pairs[i];
// Change color on collision
if (pair.bodyA.label === "Circle" && pair.bodyB.label === "Circle") {
pair.bodyA.colorChanging = true;
pair.bodyB.colorChanging = true;
}
}
}