This simple example demonstrates collisions detection between two rectangular objects. Note that this method will only work when both rectangles are axis aligned, and only with rectangles!
However, it's possible to use this approach with invisible bounding boxes around more complex shapes. In many cases, as in old arcade games, the user may not even notice the collisions are based purely on rectangles.
int rctl1X; // rectangle One x position int rctl1Y; // rectangle One y position int rctl1W = 40; // rectangle One Width int rctl1H = 70; // rectangle One Height // int rctl2X; // rectangle One x position int rctl2Y; // rectangle One y position int rctl2W = 100; // rectangle 2 Width int rctl2H = 100; // rectangle 2 Height void setup() { size(800, 600); noStroke(); rectMode(CENTER); rctl2X = width/2; rctl2Y = height/2; } void draw() { background(255); rctl1X = mouseX; rctl1Y = mouseY; boolean collision = checkCollision(rctl1X, rctl1Y, rctl1W, rctl1H, rctl2X, rctl2Y, rctl2W, rctl2H); if (collision) { fill(70, 0, 0); } else { fill(255, 0, 0); } rect(rctl1X, rctl1Y, rctl1W, rctl1H); rect(rctl2X, rctl2Y, rctl2W, rctl2H); } boolean checkCollision(int r1x, int r1y, int r1w, int r1h, int r2x, int r2y, int r2w, int r2h) { // store the locations each rectangles outer borders int top1 = r1y-r1h/2; int bottom1 = r1y+r1h/2; int right1 = r1x+r1w/2; int left1 = r1x-r1w/2; int top2 = r2y-r2h/2; int bottom2 = r2y+r2h/2; int right2 = r2x+r2w/2; int left2 = r2x-r2w/2; if (top1>bottom2 || bottom1<top2 || right1<left2 || left1>right2) { return false; } else { return true; } }
The following example demonstrates a simple method for checking collisions between round objects. As in the above example it can be used to create invisible bounding boxes for more complex shapes.
ArrayList<Ball> ballList = new ArrayList<Ball>(); Ball mouseBall; void setup() { size(600, 800); ballList.add(new Ball(width/2, height/2, 40)); mouseBall = new Ball(mouseX, mouseY, 20); } void draw() { background(255); mouseBall.update(mouseX, mouseY); for (int i = 0; i<ballList.size(); i++) { ballList.get(i).drawBall(); mouseBall.checkCollision(ballList.get(i)._position, ballList.get(i)._radius); } mouseBall.drawBall(); } class Ball { PVector _position = new PVector(); int _radius; int colour = 250; public Ball(int x, int y, int r) { _position.set(x, y, 0); _radius = r; } void update(int x, int y) { _position.set(x, y, 0); } void drawBall() { pushMatrix(); fill(colour, 0, 0); noStroke(); translate(_position.x, _position.y); ellipse(0, 0, _radius*2, _radius*2); popMatrix(); } void checkCollision(PVector position, int radius) { float distance = PVector.dist(_position, position); if (distance <= radius +_radius) { println("hit"); colour = 60; } else { colour = 255; } } }