xxxxxxxxxx
48
//reference to box2d world
let world;
//list to track fixed objects
let boundaries = [];
//list to store all the box objects
let boxes = [];
function setup() {
createCanvas(560, 390);
//initialize box2d physics and create the world
world = createWorld();
//add fixed boundaries
boundaries.push(new Boundary(width / 4, height - 5, width / 2 - 50, 10));
boundaries.push(new Boundary(3 * width / 4, height - 50, width / 2 - 50, 10));
let b = new Box(width / 2, 30);
boxes.push(b);
}
function draw() {
background(220);
//we must always step through time
let timeStep = 1.0 / 30;
//second and third arguments are velocity and position iterations
world.Step(timeStep, 10, 10);
//boxes fall from the top every so often
if (random(1) < 0.2) {
let b = new Box(width / 2, 30);
boxes.push(b);
}
//display all the boundaries
for (let i = 0; i < boundaries.length; i++) {
boundaries[i].display();
}
//display all the box objects
for (let i = boxes.length - 1; i >= 0; i--) {
boxes[i].display();
if (boxes[i].done()) {
boxes.splice(i, 1);
}
}
}