/* Demonstrates a ball in motion which bounces at the edges of the canvas. The arrow keys can be used to alter the velocity of the ball. The space key returns the ball to a relatively modest random velocity. Mouse clicking on the ball changes its color Author: Michael Goldwasser */ float cx, cy, r; // parameters for circle center (x,y) and radius float vx, vy; // velocity parameters for movement void setup() { size(500, 400); cx = 0.5*width; cy = 0.5*height; r = 0.125*min(width, height); chooseRandomVelocity(); fill(random(255), random(255), random(255)); } void chooseRandomVelocity() { vx = int(random(-5,6)); vy = int(random(-5,6)); } void draw() { background(200); ellipse(cx, cy, 2*r, 2*r); cx += vx; cy += vy; if (cx - r < 0 || cx + r > width) { vx = -vx; // flip motion horizontally } if (cy - r < 0 || cy + r > height) { vy = -vy; // flip motion vertically } } void mousePressed() { // compute square of distance from mouse press to circle center float dsq = (cx-mouseX)*(cx-mouseX) + (cy-mouseY)*(cy-mouseY); if (dsq <= r*r) { // click is within circle fill(random(255), random(255), random(255)); } } void keyPressed() { if (key == CODED) { switch (keyCode) { case LEFT: vx--; break; case RIGHT: vx++; break; case UP: vy--; break; case DOWN: vy++; break; } } else if (key == ' ') { chooseRandomVelocity(); } }