xxxxxxxxxx
const sheepArray = [];
const sheepCount = 50;
const minSheepSize = 10;
const maxSheepSize = 100;
function setup() {
createCanvas(640, 640);
for (let i = 0; i < sheepCount; i++) {
const sheep = placeRandomSheep();
sheepArray.push(sheep);
}
}
function placeRandomSheep() {
let sheep;
do {
const x = random(width);
const y = random(height);
const w = random(minSheepSize, maxSheepSize);
const h = random(minSheepSize, maxSheepSize);
sheep = new Sheep(x, y, w, h);
} while (sheep.isCollision());
return sheep;
}
function draw() {
background("white");
for (const sheep of sheepArray) {
sheep.update();
sheep.show();
}
updatePlayer();
}
function updatePlayer() {
const colour = color("orange");
colour.setAlpha(150);
noStroke();
fill(colour);
ellipse(mouseX, mouseY, 50);
}
class Sheep {
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.colour = "#"+hex(random(0xffffff),6);
}
show() {
noStroke();
fill(this.colour);
rectMode(CENTER);
rect(this.x, this.y, this.w, this.h);
}
isCollision() {
const rest = sheepArray.filter((sheep) => sheep != this);
return rest.some(
(target) =>
abs(this.x - target.x) < (this.w + target.w) / 2 &&
abs(this.y - target.y) < (this.h + target.h) / 2
);
}
update() {
const differenceX = mouseX - this.x;
const differenceY = mouseY - this.y;
const direction = [
{ x: Math.sign(differenceX), y: 0 },
{ x: 0, y: Math.sign(differenceY) }
]
if(abs(differenceX) < abs(differenceY)){
direction.reverse();
}
for(const dir of direction){
this.x += dir.x;
this.y += dir.y;
if (this.isCollision()===false) return;
this.x -= dir.x;
this.y -= dir.y;
}
}
}