pbivens67 said:
Is this code good for AABB collision detection?
Simply beautiful. Bravo, Phil! \:D/
I agree min and max is the best convention to define a box.
That's because intersection tests are usually the most used operation, and min/max is faster than corner/width or center/width conventions.
But you don't have to do this, ofc.
Btw, Aressera forgot x and y in his code example. It should be:
bool intersectRect( const Rect1& rect1, const Rect2& rect2 )
{
return rect1.minX < rect2.maxX && rect1.maxX > rect2.minX &&
rect1.minY < rect2.maxY && rect1.maxY > rect2.minY;
}
probably.
Besides, i would make it a member function of the class, so:
class Rect
{
public:
float minX, maxX, minY, maxY;
bool Intersects( const Rect1& rect2 ) const
{
return minX < rect2.maxX && maxX > rect2.minX &&
minY < rect2.maxY && maxY > rect2.minY;
}
};
This has the advantage the code is more organized.
And you don't need to remember the function name.
You just type myRect. and the code editor should list all member functions.
The const stuff also is not necessary. It's a good habit but causes some confusion initially, so you can ignore that for now.
However, i would not initialize to magic numbers such as 5 or 10.
Personally i would not initialize at all for performance reasons (but that's considered bad practice these days, since the random values can cause bugs if we forget to initialize).
It makes sense to initialize to a ‘impossible, inverted’ range, like so:
float minX = FLT_MAX, maxX = -FLT_MAX, minY = FLT_MAX, maxY = -FLT_MAX;
This may feel wrong, but it's the proper initial state if we want to calculate a bounding box from multiple points or boxes.
It also helps to spot bugs if we forget to initialize.
Otherwise, if that sounds confusing, just initialize everything to zero.
But keep in mind you have to initialize to what you actually need.
It's a data structure now, and will have many instances.
So you can no longer set your desired magic numbers just once, like you're used to from evil global variables.
Usually people use constructors to make this convenient.
I'm too lazy to type this, but you should add it.
So the usage example / testing code would be:
int main(int argc, char* args[])
{
float x1 = 5;
float y1 = 10;
float w = 5;
float h = 10;
float x2 = 7;
float y2 = 12;
Rect rect1;
rect1.minX = x1; rect1.maxX = x1+w;
rect1.minY = y1; rect1.maxY = y1+h;
Rect rect2;
rect2.minX = x2; rect2.maxX = x2+w;
rect2.minY = y2; rect2.maxY = y2+h;
bool interscts = rect1.Intersects(rect2);
if (intersects) cout << "Collision" << endl;
if (rect2.Intersects(rect1) != interscts ) cout << "Paranoia justified" << endl;
return 0;
}
In your example both rects had the same values, in case you did not notice (!)
But yeah, seems your on track to handle many objects very soon.
Rect invaders[40]; would just work. :D