<div id="p5-container"></div>
<script src="https://cdn.jsdelivr.net/npm/p5@1.10.0/lib/p5.min.js"></script>
<script>
let blocks = [];
let imgs = [];
function preload() {
imgs[0] = loadImage("URL_TO_BLOCK1");
imgs[1] = loadImage("URL_TO_BLOCK2");
imgs[2] = loadImage("URL_TO_BLOCK3");
}
function setup() {
let cnv = createCanvas(500, 500);
cnv.parent("p5-container");
rectMode(CORNER);
imageMode(CORNER);
}
function draw() {
background(200);
for (let b of blocks) b.update();
for (let b of blocks) b.draw();
}
function mousePressed() {
let img = imgs[int(random(imgs.length))];
blocks.push(new Block(mouseX, mouseY, img));
}
function keyPressed() {
if (key === " ") blocks = [];
}
class Block {
constructor(x, y, img) {
this.size = 40;
this.x = x;
this.y = y;
this.vy = 0;
this.gravity = 0.5;
this.img = img;
this.stable = false;
}
update() {
if (this.stable) return;
this.vy += this.gravity;
this.y += this.vy;
if (this.y + this.size > height) {
this.y = height - this.size;
this.vy = 0;
this.stable = true;
return;
}
for (let other of blocks) {
if (other === this) continue;
if (this.collides(other)) {
this.y = other.y - this.size;
this.vy = 0;
if (this.x + this.size < other.x + 8) this.x -= 2;
else if (this.x > other.x + other.size - 8) this.x += 2;
else this.stable = true;
break;
}
}
}
collides(other) {
return (
this.x < other.x + other.size &&
this.x + this.size > other.x &&
this.y + this.size > other.y &&
this.y < other.y + other.size
);
}
draw() {
image(this.img, this.x, this.y, this.size, this.size);
}
}
</script>