xxxxxxxxxx
67
//reference to box2d world
let world;
//list use to track fixed objects
let boundaries = [];
//a single box
let box;
//spring that will attach to the box from the mouse
let spring;
function setup() {
createCanvas(560, 390);
let text = createP("Drag and throw the box");
text.position(15, 5);
//initialize box2d physics and create the world
world = createWorld();
//make the box
box = new Box(width / 2, height / 2);
//make the spring (it doesn't really get initialized until the mouse is clicked)
spring = new Spring();
//add a bunch of fixed boundaries
boundaries.push(new Boundary(width / 2, height - 5, width, 10, 0));
boundaries.push(new Boundary(width / 2, 5, width, 10, 0));
boundaries.push(new Boundary(width - 5, height / 2, 10, height, 0));
boundaries.push(new Boundary(5, height / 2, 10, height, 0));
}
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);
//always alert the spring to the new mouse position
spring.update(mouseX, mouseY);
//draw the boundaries
for (let i = 0; i < boundaries.length; i++) {
boundaries[i].display();
}
//draw the box
box.display();
//draw the spring (it only appears when active)
spring.display();
}
//when the mouse is released, we done with the spring
function mouseReleased() {
spring.destroy();
}
//when the mouse is pressed
function mousePressed() {
//check to see if the mouse was clicked on the box
if (box.contains(mouseX, mouseY)) {
//if so, bind the mouse position to the box with a spring
spring.bind(mouseX, mouseY, box);
}
}