import java.awt.*; public class RectangleExample extends PApplet { Rectangle aRectangle; Rectangle bRectangle; int aXDirection = 1; int aYDirection = 1; int bXDirection = -1; int bYDirection = 1; color fillColor; void setup() { size(200,200); fillColor = color(0,0,0); //Rectangle(int x, int y, int width, int height) aRectangle = new Rectangle(100,100,75,50); bRectangle = new Rectangle(50,50,50,75); } void draw() { background(127); // Check the bounds of the rectangles if (aRectangle.x < 0 || aRectangle.x + aRectangle.width > width) { aXDirection = aXDirection * -1; } if (bRectangle.x < 0 || bRectangle.x + bRectangle.width > width) { bXDirection = bXDirection * -1; } if (aRectangle.y < 0 || aRectangle.y + aRectangle.height > height) { aYDirection = aYDirection * -1; } if (bRectangle.y < 0 || bRectangle.y + bRectangle.height > height) { bYDirection = bYDirection * -1; } if (aRectangle.intersects(bRectangle)) { aYDirection *= -1; aXDirection *= -1; bYDirection *= -1; bXDirection *= -1; } aRectangle.x += aXDirection; aRectangle.y += aYDirection; bRectangle.x += bXDirection; bRectangle.y += bYDirection; fill(fillColor); //draw the rects using the regular processing drawing routine rect(aRectangle.x, aRectangle.y, aRectangle.width, aRectangle.height); rect(bRectangle.x, bRectangle.y, bRectangle.width, bRectangle.height); } void mousePressed() { // Easier than using the width, height and comparing the mouse position if (aRectangle.contains(mouseX,mouseY)) { fillColor = color(255,255,255); aYDirection *= -1; aXDirection *= -1; } else if (bRectangle.contains(mouseX,mouseY)) { fillColor = color(255,255,255); bYDirection *= -1; bXDirection *= -1; } } void mouseReleased() { // Easier than using the width, height and comparing the mouse position if (aRectangle.contains(mouseX,mouseY)) { fillColor = color(0,0,0); } else if (bRectangle.contains(mouseX,mouseY)) { fillColor = color(0,0,0); } } }