class Ball{ float x,y,vx,vy,radius,diameter; int type; Table table; color ballColor; //-------------- Ball(float x, float y, int type, Table t){ this.x = x; this.y = y; this.type = type; diameter = 12; radius = diameter/2; table = t; ballColor = table.ballColors[type]; } //-------------- void update(){ vx *= table.drag; vy *= table.drag; x += vx; y += vy; wallBounce(); } //-------------- void wallBounce(){ if(xgame.width-radius){ vx = -table.wallElasticity*vx; x = table.width-radius; } if(ygame.height-radius){ vy = -table.wallElasticity*vy; y = table.height-radius; } } //-------------- void visualize(){ fill(ballColor); stroke( 0.5*red(ballColor), 0.5*green(ballColor), 0.5*blue(ballColor) ); stroke(255); ellipse(x,y,diameter,diameter); } //-------------- void push(float dx, float dy){ vx += dx; vy += dy; } //-------------- void collisionDetect(Ball b){ float distance = dist(x,y,b.x,b.y); if( distance < diameter ){ float vxSum = 0.5*(vx + b.vx); float vySum = 0.5*(vy + b.vy); float forceMag = ((b.x-x)*(vx-vxSum) + (b.y-y)*(vy-vySum)); float xForce = 0.25*(x-b.x)*forceMag/distance; float yForce = 0.25*(y-b.y)*forceMag/distance; vx = vx + table.elasticity * xForce; vy = vy + table.elasticity * yForce; b.vx = b.vx - table.elasticity * xForce; b.vy = b.vy - table.elasticity * yForce; b.x = x + (diameter+1)*(b.x-x)/distance; b.y = y + (diameter+1)*(b.y-y)/distance; } } }