xxxxxxxxxx
83
const canvasWidth = 400;
const canvasHeight = 400;
const ground = canvasHeight*5/7;
let block1, block2;
let massConsts = [];
let collisionCount = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
block1 = new Block(1, 20, 0);
block2 = new Block(10000, 30, -.5);
massConsts.push((block1.mass-block2.mass)/(block1.mass+block2.mass));
massConsts.push((2*block2.mass)/(block1.mass+block2.mass));
massConsts.push((2*block1.mass)/(block1.mass+block2.mass));
massConsts.push((block2.mass-block1.mass)/(block1.mass+block2.mass));
console.log(massConsts);
}
function draw() {
background(220);
line(0,ground,canvasWidth,ground);
block1.display();
block2.display();
moveBlocks();
}
function moveBlocks(){
block1.move();
block2.move();
Block.collision(block1,block2);
end();
}
function end(){
if (block1.v > 0 && block2.v > block1.v){
console.log('finished');
noLoop();
}
}
class Block{
constructor(m=1, x=50, v=1){
this.mass = m;
this.x = x;
this.v = v;
}
static get length(){
return 10;
}
display(){
square(this.x,ground-Block.length,Block.length);
}
move(){
this.x += this.v;
if (this.x <= 0){
console.log(++collisionCount);
this.x = 0;
this.v = -this.v;
}
// if (this.x+Block.length >= canvasWidth){
// this.x = canvasWidth-Block.length;
// this.v = -this.v;
// }
}
static collision(left, right){
if (block2.x <= block1.x + Block.length){
if (block2.v <= 0)
block2.x = block1.x + Block.length;
else
block1.x = block2.x - Block.length;
let v1 = block1.v;
let v2 = block2.v;
block1.v = massConsts[0]*v1 + massConsts[1]*v2;
block2.v = massConsts[2]*v1 + massConsts[3]*v2;
console.log(++collisionCount);
}
}
}