...
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.
Code Block | ||
---|---|---|
| ||
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); } // this method uses the center of the rectangles boolean checkCollision(int r1x, int r1y, int r1w, int r1h, int r2x, int r2y, int r2w, int r2h) { // store the locations of 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; } } |
Rectangular Collision
This method uses the top left original of the rectangle and width and height to calculate the collision.
Code Block | ||
---|---|---|
| ||
boolean checkRectangle( float r1x, float r1y, float r1w, float r1h, float r2x, float r2y, float r2w, float r2h) { return (r1x < r2x + r2w && r1x + r1w > r2x && r1y < r2y + r2h && r1y + r1h > r2y); } |
Circular Collision
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.
...