xxxxxxxxxx
57
function Ball(x, y, mass) {
this.px = x;
this.py = y;
this.vx = 0;
this.vy = 0;
this.mass = mass;
}
Ball.prototype.collide = function(other) {
this.vx = (this.mass - other.mass) / (this.mass + other.mass) * this.vx;
this.vy = (this.mass - other.mass) / (this.mass + other.mass) * this.vy;
}
Ball.prototype.applyForce = function(x, y) {
this.vx += x;
this.vy += y;
}
Ball.prototype.update = function() {
this.vx / this.mass;
this.vy / this.mass;
this.px += this.vx;
this.py += this.vy;
}
Ball.prototype.draw = function() {
circle(this.px, this.py, 32);
}
var balls;
function setup() {
createCanvas(480, 320);
balls = [];
for(var i = 0; i < 1; i++) {
balls.push(new Ball(random(0, width), random(0, height / 2), random(2)));
}
}
function draw() {
background(220);
for(var i = 0; i < balls.length; i++) {
var ball = balls[i];
ball.applyForce(0, 2);
ball.update();
if(ball.px < 16 || ball.px > width - 16)
ball.vx = -ball.vx;
if(ball.py < 16 || ball.py > height - 16)
ball.vy = -ball.vy;
for(var j = 0; j < balls.length; j++) {
if(j === i) continue;
ball.collide(balls[j]);
}
ball.draw();
}
}