xxxxxxxxxx
108
let Engine = Matter.Engine,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body,
Events = Matter.Events; // Include the Events module
let engine;
let circles = []; // This will now hold objects with both the body and color
let world;
let particles = []; // Array to hold background particles
function setup() {
createCanvas(windowWidth, windowHeight);
engine = Engine.create();
world = engine.world;
engine.world.gravity.y = 0; // Set gravity to 0 for a floating effect
// Add walls - optional, depending on whether you want boundaries
let options = { isStatic: true, restitution: 1.0 };
World.add(world, [
Bodies.rectangle(width / 2, 0, width, 50, options), // Top
Bodies.rectangle(width / 2, height, width, 50, options), // Bottom
Bodies.rectangle(0, height / 2, 50, height, options), // Left
Bodies.rectangle(width, height / 2, 50, height, options) // Right
]);
// Initial circles
addCircle();
// Randomly add new circles
setInterval(() => {
addCircle();
}, random(500, 1000)); // Randomly between 1-5 seconds
// Create background particles
for (let i = 0; i < 100; i++) { // Adjust number of particles as needed
particles.push({
x: random(width),
y: random(height),
size: random(1, 3),
color: getRandomColor()
});
}
// Listen for collisions
Events.on(engine, 'collisionStart', function(event) {
var pairs = event.pairs;
pairs.forEach(function(pair) {
const bodyA = circles.find(c => c.body === pair.bodyA);
const bodyB = circles.find(c => c.body === pair.bodyB);
if (bodyA && bodyB) {
bodyA.color = getRandomColor();
bodyB.color = getRandomColor();
}
});
});
}
function draw() {
background(0);
Engine.update(engine);
// Draw background particles
particles.forEach(particle => {
fill(particle.color);
noStroke();
ellipse(particle.x, particle.y, particle.size);
});
// Draw circles with their unique colors
circles.forEach(circleObj => {
fill(circleObj.color);
noStroke();
ellipse(circleObj.body.position.x, circleObj.body.position.y, circleObj.body.circleRadius * 2);
});
}
function mouseClicked() {
addCircle(mouseX, mouseY);
}
function addCircle(x = random(width), y = random(height)) {
let radius = random(10, 50);
let circle = Bodies.circle(x, y, radius, {
restitution: 0.9, // Bounciness
friction: 0.1,
frictionAir: 0.01,
density: 0.001, // Lower density for slower motion
});
// Assign a unique color
let color = getRandomColor();
circles.push({ body: circle, color: color }); // Store the circle along with its color
World.add(world, circle);
// Apply an initial random force to simulate drifting galaxies
Body.applyForce(circle, circle.position, {x: random(-0.5, 0.5), y: random(-0.5, 0.5)});
}
function getRandomColor() {
// Generate a random color
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}