xxxxxxxxxx
import java.util.*;
//Ball b = new Ball(100, 200, 30);
//ArrayList<Ball> balls = new ArrayList<Ball>();
//balls.add(b);
Ball[] balls = {new Ball(100, 200, 30, 1.3, 0)};
void setup() {
size(600, 600);
smooth();
balls = ((Ball[])append(balls, new Ball(300, 200, 30, -1.3, 0)));
}
void draw() {
background(255);
noStroke();
for (int i=balls.length -1; i > -1; i--) {
balls[i].move();
balls[i].checkBoundryCollision();
balls[i].checkObjectCollision(balls, i);
balls[i].show();
balls[i].move();
}
}
void mousePressed() {
float r = random(1,50);
balls = ((Ball[])append(balls, new Ball(mouseX, mouseY, r, random(-3.5, 3.5), random(-3.5, 3.5))));
}
class Ball {
private float x, y, vx, vy, r, m;
private int c;
private Boolean hit;
Ball() {
}
Ball(float x, float y, float r, float vx, float vy) {
this.x = x;
this.y = y;
this.r = r;
this.m = r*.1;
this.vx = vx;
this.vy = vy;
this.hit = false;
this.c = (int)random(0, 240);
}
void show() {
if (hit) {
fill(200, 10, 10);
} else {
fill(c);
}
ellipse(this.x, this.y, this.r* 2, this.r* 2);
this.hit = false;
}
void move() {
this.x += this.vx;
this.y += this.vy;
}
void checkObjectCollision(Ball[] balls, int index) {
for (int i = balls.length -1; i>-1; i--) {
if (i!= index) {
stroke(balls[i].c);
strokeWeight(.5);
line(this.x, this.y, balls[i].x, balls[i].y); //draw line between balls
float d = dist(this.x, this.y, balls[i].x, balls[i].y);
if (d < this.r + balls[i].r) {
//calculate final velocities based on law of conservation of momentum
PVector finalVel0 = new PVector();
PVector finalVel1 = new PVector();
finalVel0.x = ((this.m - balls[i].m) * this.vx + 2 * balls[i].m * balls[i].vx) / (this.m + balls[i].m);
finalVel1.x = ((balls[i].m - this.m) * balls[i].vx + 2 * this.m * this.vx) / (this.m + balls[i].m);
finalVel0.y = ((this.m - balls[i].m) * this.vy + 2 * balls[i].m * balls[i].vy) / (this.m + balls[i].m);
finalVel1.y = ((balls[i].m - this.m) * balls[i].vy + 2 * this.m * this.vy) / (this.m + balls[i].m);
//swap velocities
this.vx = finalVel0.x;
balls[i].vx = finalVel1.x;
this.vy = finalVel0.y;
balls[i].vy = finalVel1.y;
//PVector vTemp = new PVector();
//vTemp.x = this.vx;
//this.vx = balls[i].vx;
//balls[i].vx = vTemp.x;
//vTemp.y = this.vy;
//this.vy = balls[i].vy;
//balls[i].vy = vTemp.y;
this.hit = true;
}
}
}
}
void checkBoundryCollision() {
//right edge of screen
if (this.x > width - this.r) {
this.x = width - this.r;
this.vx *= -1;
}
if (this.x < this.r) {
this.x = this.r;
this.vx *= -1;
}
if (this.y > height - this.r) {
this.y = height - this.r;
this.vy *= -1;
}
if (this.y < this.r) {
this.y = this.r;
this.vy *= -1;
}
}
}