xxxxxxxxxx
95
let Engine = Matter.Engine,
World = Matter.World,
Bodies = Matter.Bodies;
let engine;
let world;
let platforms = [];
let balls = [];
let currentPlatform = null;
let ballSpawnInterval;
function setup() {
frameRate(120);
createCanvas(800, 2100);
colorMode(HSB, 360, 100, 100); // Initialize HSB color mode
// Create an engine and world
engine = Engine.create();
world = engine.world;
engine.world.gravity.y = 1; // Set gravity
// Set interval for spawning balls
ballSpawnInterval = setInterval(spawnBall, 300); // Spawn a ball every 300 milliseconds
}
function draw() {
background(0, 6);
Engine.update(engine);
// Draw platforms
platforms.forEach(platform => {
if (platform.body) {
fill(200);
push();
translate(platform.body.position.x, platform.body.position.y);
rotate(platform.body.angle);
rectMode(CENTER);
rect(0, 0, platform.width, 10);
pop();
}
});
// Draw balls with color logic based on y-axis
balls.forEach(ball => {
let hue = map(ball.position.y, 0, height, 0, 360) % 360;
fill(360-hue, 100, hue);
noStroke();
ellipse(ball.position.x, ball.position.y, ball.circleRadius * 2, ball.circleRadius * 2);
});
colorMode(RGB, 255);
}
function mousePressed() {
if (!currentPlatform) {
currentPlatform = { start: createVector(mouseX, mouseY), end: null, body: null };
} else if (!currentPlatform.end) {
currentPlatform.end = createVector(mouseX, mouseY);
createPlatform(currentPlatform);
platforms.push(currentPlatform);
currentPlatform = null;
}
}
function keyPressed() {
if (keyCode === 32) { // Check if the spacebar is pressed
if (platforms.length > 0) {
let latestPlatform = platforms.pop(); // Remove the latest platform from the array
World.remove(world, latestPlatform.body);
}
}
}
function createPlatform(platform) {
let centerX = (platform.start.x + platform.end.x) / 2;
let centerY = (platform.start.y + platform.end.y) / 2;
let length = dist(platform.start.x, platform.start.y, platform.end.x, platform.end.y);
let angle = atan2(platform.end.y - platform.start.y, platform.end.x - platform.start.x);
platform.body = Matter.Bodies.rectangle(centerX, centerY, length, 10, { isStatic: true });
Matter.Body.setAngle(platform.body, angle);
World.add(world, platform.body);
platform.width = length;
}
function spawnBall() {
let radius = 20;
let x = width / 2;
let y = 50;
let ball = Matter.Bodies.circle(x, y, radius, { restitution: 1.1 });
balls.push(ball);
World.add(world, ball);
}