2d collison detection of rectangles?
in
Programming Questions
•
2 years ago
I've been working on this all night. I have an array of 10 Rectangle objects. A rectangle has data values x,y,w,h which represent the X,Y location of the rectangle and it's height and width. no rectMode(); calls are used. I'm using this algorithm I found to try to detect collision between any of the 10 rects colliding as they move about:
- boolean collDetect(Rectangle rect1, Rectangle rect2) { // this will be collison detection
if (rect1.x+rect1.w < rect2.x) { return false; }
if (rect1.x > rect2.x+rect2.w) { return false; }
if (rect1.y+rect1.h < rect2.y) { return false; }
if (rect1.y > rect2.y+rect2.h) { return false; }
return true;
}
- for (int iii=0; iii <= 9; iii++) {
for (int jjj=0; jjj<= 9; jjj++) {
if (iii != jjj) { //not the same rect
boolean coll = collDetect(myRects[iii],myRects[jjj]);
if (coll == true) {
myRects[iii].rectColor = color(255,0,0);
myRects[jjj].rectColor = color(255,0,0);
} else {
myRects[iii].rectColor = color(0);
myRects[jjj].rectColor = color(0);
}
}
}
}
- //TODO: Fix it so that they don't all fall into a state of just going one direc
//TODO: do this by checking if movement is 0 on every boundry hit and reassign
//TODO: if it is.
final int windowSize = 500;
Rectangle[] myRects;
int locationX, locationY;
void setup () {
myRects = new Rectangle[10];
for (int iii=0; iii <= 9; iii++) {
locationX = int(random(windowSize));
locationY = int(random(windowSize));
myRects[iii] = new Rectangle(locationX, locationY);
}
size(windowSize,windowSize);
noStroke();
}
void draw () {
background(0,100,100);
for (int iii=0; iii <= 9; iii++) {
myRects[iii].update();
for (int jjj=0; jjj<= 9; jjj++) {
if (iii != jjj) { //not the same rect
boolean coll = collDetect(myRects[iii],myRects[jjj]);
if (coll == true) {
myRects[iii].rectColor = color(255,0,0);
myRects[jjj].rectColor = color(255,0,0);
} else {
myRects[iii].rectColor = color(0);
myRects[jjj].rectColor = color(0);
}
}
}
}
}
boolean collDetect(Rectangle rect1, Rectangle rect2) { // this will be collison detection
if (rect1.x+rect1.w < rect2.x) { return false; }
if (rect1.x > rect2.x+rect2.w) { return false; }
if (rect1.y+rect1.h < rect2.y) { return false; }
if (rect1.y > rect2.y+rect2.h) { return false; }
return true;
}
class Rectangle {
int x; //position
int y;
int h;
int w;
int mvmntx;
int mvmnty;
color rectColor = color(0,0,0);
Rectangle (int c1x, int c1y) {
x = c1x;
y = c1y;
h = 20;
w = 20;
mvmntx = round(random(-2,3)); //movement
mvmnty = round(random(-2,3));
void boundryCheck() {
if (x < 0) {
mvmntx = round(random(1,3));
}
if (y < 0) {
mvmnty = round(random(1,3));
}
if (x+w > windowSize) {
mvmntx = round(random(-2,0));
}
if (y+h > windowSize) {
mvmnty = round(random(-2,0));
}
}
void moveRect() {
x = x+mvmntx;
y = y+mvmnty;
}
void render () {
fill(rectColor);
rect(x,y,w,h);
}
void update() {
boundryCheck();
moveRect();
render();
}
}
1