reason is, when x2 < x1 it still looks like a normal rectangle, but your lower right corner is left from your upper right corner so both corners are swapped.
And then your ifs won’t work I guess
Code
here is my way is collision detection according to the link above:
//int time;
//coordinates for drawing rectangles
float x1;
float y1;
float x2;
float y2;
void setup() {
size(400, 400);
background(255);
//turn of any fill
noFill();
// frameRate(3);
}
void draw() {
stroke(0, 255, 0); //green
rect(width/2-100, height/2-100, 200, 200);
x1 = random(0, width-10);
y1 = random(0, height-10);
x2 = random(x1+1, width);
y2 = random(y1+1, height);
// if ok
if (!intersectionRectRect (
width/2-100, height/2-100, 200, 200,
x1, y1, x2-x1, y2-y1)) {
//draw rectangles based on x,y coordinates in each quad
stroke(0);
//upper left
line(x1, y1, x2, y1);
line(x2, y1, x2, y2);
line(x2, y2, x1, y2);
line(x1, y2, x1, y1);
}
}
//----------------------------------------------------------------------------------
// RECTANGLE/RECTANGLE intersection
boolean intersectionRectRect(float r1x, float r1y, float r1w, float r1h,
float r2x, float r2y, float r2w, float r2h) {
// are the sides of one rectangle touching the other?
if (r1x + r1w >= r2x && // r1 right edge past r2 left
r1x <= r2x + r2w && // r1 left edge past r2 right
r1y + r1h >= r2y && // r1 top edge past r2 bottom
r1y <= r2y + r2h) { // r1 bottom edge past r2 top
return true;
}
return false;
}