// Variance int dia = 20; //diameter float[] posX = {10.0, 300.0}; //position X float[] posY = {290.0, 290,0}; //position Y //speed X = (290*9.8/59)/(2*spdY[0]) float[] spdX = {2.497244, 0.0}; //speed Y =SQRT(2*9.8/59*280) float[] spdY = {-9.644529, 0.0} ; int[][] col = {{255,128,0}, {0, 128, 255}}; float[] mass = {1.0, 1.0} ; //weight float[] elast = {1.0, 1.0} ; //elast int flagK = 0; //flag by keyboard float GRAV = 9.8; //gravity void setup(){ // Initialize size(400, 300); //window background(0, 0, 0); //black noStroke(); //lineless frameRate(60); } void draw() { fill(0,0,0); //clear color rect(0, 0, width, height); if (flagK == 0) { //watch at flag //draw balls for(int i=0;i<2;i++) { fill(col[i][0],col[i][1],col[i][2]); //circle color ellipse(posX[i], posY[i], dia, dia); //circle } } else { collisionDetect(); posX[0] += spdX[0]; spdY[0] += GRAV/60; // gravity posY[0] += spdY[0]; if( posY[0] >= height-dia/2 ) { posY[0] = height-dia/2; } fill(col[0][0],col[0][1],col[0][2]); //circle color ellipse(posX[0], posY[0], dia, dia); //circle posX[1] += spdX[1]; posY[1] += spdY[1]; fill(col[1][0],col[1][1],col[1][2]); //circle color ellipse(posX[1], posY[1], dia, dia); //circle } } void keyPressed() { if (key == ' ') { //space flagK = 1; //clear mode set } } void collisionDetect(){ //distance of balls float bpx = posX[1] - posX[0]; float bpy = posY[1] - posY[0]; float dd = dist(0, 0, bpx, bpy); if( dd <= dia ){ //Angle along X axis float theta = atan2(bpy, bpx); float sint = sin(theta); float cost = cos(theta); //Direction of ball0 float tvx0 = cost*spdX[0] + sint*spdY[0]; float tvy0 = - sint*spdX[0] + cost*spdY[0]; //Direction of ball1 float tvx1 = cost*spdX[1] + sint*spdY[1]; float tvy1 = - sint*spdX[1] + cost*spdY[1]; //Mass & coffeient float m0 = mass[0]; float m1 = mass[1]; float conf = elast[0]* elast[1]; //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 spdX[0] = cost*tvx0n - sint*tvy0; spdY[0] = sint*tvx0n + cost*tvy0; spdX[1] = cost*tvx1n - sint*tvy1; spdY[1] = sint*tvx1n + cost*tvy1; } }