/* title: bouncing ball description: ball deflects off sketch window edges created: August 9, 2005 by: Ira Greenberg modified: With 3 balls, and initial random ball placement, Sept. 13, 2006 by Fred Green */ // declare global variables int x1speed, y1speed; int x2speed, y2speed; int x1pos, y1pos, x2pos, y2pos, wdth, ht; int x3speed, y3speed, x3pos, y3pos; //initialize sketch void setup(){ //set sketch window size and background color size(500, 400); background(0); //ball speed x1speed = 3; y1speed = 4; //other ball speed x2speed = 5; y2speed = 6; x3speed = 7; y3speed = 8; //ball size wdth = 20; ht = 20; // turn off shape stroke rendering noStroke(); //initial ball placement x1pos = (int)random(10, width-10); y1pos = (int)random(10, height-10); x2pos = (int)random(10, width-10); y2pos = (int)random(10, height-10); x3pos = (int)random(10, width-10); y3pos = (int)random(10, height-10); //set the animation loop speed frameRate(30); } // begin animation loop void draw(){ //update background background(0); //draw balls fill(200, 200, 0); ellipse(x1pos, y1pos, wdth, ht); ellipse(x2pos, y2pos, wdth, ht); ellipse(x3pos, y3pos, wdth, ht); //upgrade position values x1pos+=x1speed; y1pos+=y1speed; x2pos+=x2speed; y2pos+=y2speed; x3pos+=x3speed; y3pos+=y3speed; //Detect collisions with walls: detectCollisions(); } void detectCollisions() { if (x1pos>=width-wdth/2 || x1pos<=wdth/2){ x1speed*=-1; } if (y1pos>=height-ht/2 || y1pos<=ht/2){ y1speed*=-1; } if (x2pos>=width-wdth/2 || x2pos<=wdth/2){ x2speed*=-1; } if (y2pos>=height-ht/2 || y2pos<=ht/2){ y2speed*=-1; } if (x3pos>=width-wdth/2 || x3pos<=wdth/2){ x3speed*=-1; } if (y3pos>=height-ht/2 || y3pos<=ht/2){ y3speed*=-1; } }