xxxxxxxxxx
110
let mChar;
let charDiam = 50;
let moveDist = 2;
let obstacles = [];
let maxObstacleDiam = 50;
let rewards = [];
let rewardDiam = 10;
let maxRewardCount = 12;
function overlap(o0, o1) {
let d = sqrt((o1.x - o0.x) ** 2 + (o1.y - o0.y) ** 2);
return d < o0.d / 2 + o1.d / 2;
}
function getObstacleDiam() {
return random(maxObstacleDiam / 2, maxObstacleDiam);
}
function addObject(objArray, objDiam) {
let rX = random(mChar.x + mChar.d, mChar.x + width);
let rY = random(mChar.y + mChar.d, mChar.y + height);
objArray.push({
x: rX % width,
y: rY % height,
d: objDiam,
});
}
function setup() {
createCanvas(windowWidth, windowHeight);
mChar = {
x: width / 2,
y: height / 2,
d: charDiam,
};
addObject(rewards, rewardDiam);
addObject(obstacles, getObstacleDiam());
}
function draw() {
background(220, 20, 120);
if (keyIsPressed) {
keyPressed();
}
fill(255, 0, 0);
for (let i = 0; i < obstacles.length; i++) {
// overlap with obstacle
if (overlap(mChar, obstacles[i])) {
obstacles.splice(i, 1);
mChar.d = max(mChar.d - 10, 0);
addObject(obstacles, getObstacleDiam());
addObject(obstacles, getObstacleDiam());
} else {
ellipse(obstacles[i].x, obstacles[i].y, obstacles[i].d);
}
}
fill(20, 220, 250);
for (let i = 0; i < rewards.length; i++) {
// overlap with reward
if (overlap(mChar, rewards[i])) {
rewards.splice(i, 1);
mChar.d += 5;
addObject(obstacles, getObstacleDiam());
addObject(rewards, rewardDiam);
if (rewards.length < maxRewardCount) {
if (random() < 0.3333) {
addObject(rewards, rewardDiam);
}
if (random() < 0.12) {
addObject(rewards, rewardDiam);
}
}
} else {
ellipse(rewards[i].x, rewards[i].y, rewards[i].d);
}
}
fill(255, 190, 90);
ellipse(mChar.x, mChar.y, mChar.d);
}
function keyPressed() {
if (keyCode == UP_ARROW) {
mChar.y -= moveDist;
} else if (keyCode == DOWN_ARROW) {
mChar.y += moveDist;
} else if (keyCode == LEFT_ARROW) {
mChar.x -= moveDist;
} else if (keyCode == RIGHT_ARROW) {
mChar.x += moveDist;
} else if (key == "r") {
mChar.x = width / 2;
mChar.y = height / 2;
}
}