xxxxxxxxxx
const detail = 2 / 1000;
const groundItemDiameter = 10;
let scrollTime = 0;
const palette = [
'#D64933',
'#FA8334',
'#EA9010',
'#2D854A',
'#14591D',
'#3587A4',
'#23B5D3',
'#70587C',
'#573280',
'#832232',
'#DA4167',
'#E87461'
];
let colors = [];
const {
Engine,
World,
Bodies,
Body,
Composite
} = Matter;
let engine, box1, world;
let boxes = [];
let groundItems = [
[],
[],
[]
];
function setup() {
createCanvas(windowWidth, windowHeight);
engine = Engine.create()
world = engine.world
createGroundLayer(0);
createGroundLayer(1);
createGroundLayer(2);
colors.push(random(palette), random(palette), random(palette));
}
function drawTextHUD() {
push()
fill("#fffbe6")
text("balls: " + boxes.length, 30, 30)
pop()
}
function createGroundLayer(n) {
for (let x = 0; x <= width + groundItemDiameter; x += groundItemDiameter) {
const y = calcHeightForXAndTime(x, scrollTime, n);
groundItems[n].push(new GroundItem(x, y, groundItemDiameter, n));
}
}
function calcHeightForXAndTime(x, t, n) {
return map(noise((x + t) * detail), 0, 1, height, 50 * 5 * n);
}
function updateGroundItems() {
for (let i = 0; i < 3; i++) {
for (const ground of groundItems[i]) {
const x = ground.body.position.x;
const y = calcHeightForXAndTime(x + 1000 * i, scrollTime, i);
Body.setPosition(ground.body, {
x,
y
})
}
}
}
function updateBoxes() {
boxes.forEach(b => b.update());
const [toRemove, toKeep] = partition(boxes, b => b.isDead)
boxes = toKeep;
toRemove.forEach(b => Composite.remove(world, b.body))
}
/** split a given array into two arrays, according to the results of a predicate function applied to each element */
function partition(inputArr, testFn) {
const arrA = []
const arrB = []
for (const item of inputArr) {
const passes = testFn(item);
(passes ? arrA : arrB).push(item)
}
return [arrA, arrB]
}
function drawGroundItems(n) {
//show a circle for each groundItem
for (const groundItem of groundItems[n]) {
groundItem.show()
}
//draw the filled-in shape under the ground
let c1 = "#fffbe6";
let c2 = "#050505";
if (n % 2 === 1) {
fill(c2);
} else {
fill("#fffbe6");
}
beginShape()
vertex(-50, height + 50);
vertex(-50, groundItems[n][0].body.position.y);
for (const groundItem of groundItems[n]) {
vertex(groundItem.body.position.x, groundItem.body.position.y);
}
vertex(width + 50, groundItems[n].at(-1).body.position.y);
vertex(width + 50, height + 50);
endShape();
}
function drawBoxes() {
for (const box of boxes) {
box.show()
}
}
function draw() {
background("#050505");
noStroke();
Engine.update(engine)
updateGroundItems();
drawGroundItems(0);
drawGroundItems(1);
drawGroundItems(2);
drawBoxes();
drawTextHUD()
updateBoxes()
scrollTime += groundItemDiameter / 10;
}
function mouseDragged() {
boxes.push(new Box(mouseX, mouseY, 50));
}