// Variance int numBall = 20; Ball[] maru = new Ball[numBall]; int[][] iro = new int[numBall][3]; float[][] spd = new float[numBall][3]; float[][] pos = new float[numBall][3]; float dm = 20.0; void setup() { size(400, 400); //window background(0, 0, 0); //black noStroke(); //lineless for (int i = 0; i < numBall; i++) { for (int j=0; j<3; j++ ) { iro[i][j] = (int)(random(1)*255); spd[i][j] = random(-1,1); pos[i][j] = 180*random(-1,1)+200; } maru[i] = new Ball(pos[i][0], pos[i][1], dm, spd[i][0], spd[i][1], iro[i]); } } void draw(){ fill(0,0,0); //clear color rect(0, 0, width, height); for (int i = 0; i < numBall; i++) { collisionDetect(i); maru[i].move(width, height); maru[i].display(); } } void collisionDetect(int i) { for (int k = 0; k < numBall; k++ ) { if ( k != i ) { float bpx = maru[i].px - maru[k].px; float bpy = maru[i].py - maru[k].py; float dd = dist(0, 0, bpx, bpy); //distance of balls if( dd <= dm ){ maru[i].collision(k); } } } } class Ball { float px, py; //position float vx, vy; //velocity float dia; //diameter int[] col = {}; Ball(float x, float y, float d) { px = x; py = y; dia = d; } Ball(float x, float y, float d, int[] c) { px = x; py = y; dia = d; col = c; } Ball(float x, float y, float d, float sx, float sy, int[] c) { px = x; py = y; dia = d; vx = sx; vy = sy; col = c; } void display() { fill(col[0], col[1], col[2]); ellipse(px, py, dia, dia); } void display(int[] col) { fill(col[0], col[1], col[2]); ellipse(px, py, dia, dia); } void move(int w, int h) { int fx = 1; int fy = 1; if (px <= dia/2 || px >= w-dia/2 ) { fx *= -1; } if (py <= dia/2 || py >= h-dia/2 ) { fy *= -1; } vx *= fx; vy *= fy; px += vx; py += vy; } void collision(int k) { Ball other = (Ball)maru[k]; float bpx = this.px - other.px; float bpy = this.py - other.py; //Angle along X axis float theta = atan2(bpy, bpx); float sint = sin(theta); float cost = cos(theta); //Direction of ball0 float tvx0 = cost*this.vx + sint*this.vy; float tvy0 = - sint*this.vx + cost*this.vy; //Direction of ball1 float tvx1 = cost*other.vx + sint*other.vy; float tvy1 = - sint*other.vx + cost*other.vy; //Mass & coffeient float m0 = 1.0; float m1 = 1.0; float conf = 1.0 ; //Velocity based on conservation of momentum float tvx0n = ( ( m0 - conf*m1 ) * tvx0 + m1 * ( 1 + conf ) * tvx1 ) / ( m0 + m1 ); float tvx1n = ( m0 * ( 1 + conf ) * tvx0 + ( m1 - conf*m0 ) * tvx1 ) / ( m0 + m1 ); //Velocity each Ball this.vx = cost*tvx0n - sint*tvy0; this.vy = sint*tvx0n + cost*tvy0; other.vx = cost*tvx1n - sint*tvy1; other.vy = sint*tvx1n + cost*tvy1; } }