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 boolean grabbed=false; // whether I have been grabbed by the mouse // 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); if(grabbed) { fill(red(c)/2,green(c)/2,blue(c)/2); ellipse(x,y,r,r); } } 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 updateGrabbed() { // if I am not grabbed yet, grab me if the mouse is clicked on me if(!grabbed) grabbed = mousePressed && dist(mouseX,mouseY,x,y) < r; // otherwise stop grabbing me when I release the mouse else grabbed = mousePressed; } void update() { // check if grabbed updateGrabbed(); // follow the mouse if grabbed if(grabbed) { x = mouseX; y = mouseY; vx = mouseX - pmouseX; vy = mouseY-pmouseY; } else {// obey physics otherwise // update the velocity updateVelocity(); // Move in the appropriate direction by the step size x += vx; y += vy; // bounce bounce(); } } }