class PhysBall { float x, y; // position float vx=0, vy=0; // velocity in the two directions float r=10; // radius color c=color(255); // color float gravity=0.1; // the amount of acceleration float drag=0.99; // multiplicative factor for velocity float frict=0.75; // multiplicative factor, only when bounce // Initialize a Ball at position (x0,y0) PhysBall(float x0, float y0, color c0) { x = x0; y = y0; c = c0; } void draw() { fill(c); stroke(red(c)/2,green(c)/2,blue(c)/2); ellipse(x,y,r*2,r*2); } void updateVelocity() { // Accelerate according to gravity vy += gravity; // Now damp according to drag vx *= drag; vy *= drag; } void bounce() { if (x > width-r || x < r) { x = constrain(x,r,width-r); vx = -vx; vy *= frict; // damp } if (y > height-r || y < r) { y = constrain(y,r,height-r); vy = -vy; vy *= frict; // damp } } void update() { // update the velocity updateVelocity(); // Move in the appropriate direction by the step size x += vx; y += vy; // bounce bounce(); } }