Skip to main content
gamedev.net
🔒 Locked

Basic Collision Detection

Started by Tarviathun 2 replies 1k views
Original Post
Tarviathun
Tarviathun
I know a whole bunch of n00bs ask this a lot, but it's 5:30 in the morning and I have forgotten the most basic collision code of all. The collision between two rectangles. I don't want to piss anyone off, but I've been thinking about it for a while and either the Mountain Dew just isn't working or my brain is dead, or both. What would be the code to detect the intersection of two rectangles? I'm sorry about this. I'm sorta embarassed.
erichardson
erichardson
It would help to know what language you are using. But basically do the following:

Take each corner of the first rectangle in turn and see if it is inside the second rectangle...Yes: HIT! No: Carry on to the next corner...

When all corners are exhausted and none of them are HITS, then you don't have an intersection.

The Win32 API provides IntersectRect which not only tells you if there was an intersection between two rectangles but also returns the product of that intersection as another rectangle.

RECT rcOne, rcTwo, rcResult;SetRect(&rcOne, 0, 0, 100, 100);SetRect(&rcTwo, 50, 50, 200, 200);BOOL bHit = IntersectRect(&rcResult, &rcOne, &rcTwo);
oliii
oliii
the code would be like...

bool IntersectAreas(const Vector& MinA, const Vector& MaxA, const Vector& MinB, const Vector& MaxB, Vector& MinR, Vector& MaxR){    MinR.x = Max(MinA.x, MinB.x);    MinR.y = Max(MinA.y, MinB.y);    MinR.z = Max(MinA.z, MinB.z);    MaxR.x = Min(MaxA.x, MaxB.x);    MaxR.y = Min(MaxA.y, MaxB.y);    MaxR.z = Min(MaxA.z, MaxB.z);    if (MinR.x > MaxR.x) return false;    if (MinR.y > MaxR.y) return false;    if (MinR.z > MaxR.z) return false;    return true;}


MinA, MaxA is the area (or volume, since this is in 3D) of the first box.
MinB, MaxB is the area (or volume, since this is in 3D) of the second box.
MinR, MaxR is the resulting intersection area/volume.
Everything is better with Metal.
Tarviathun
Tarviathun
Thanks for the help. I'm writing a 2D RTS engine in C++, but I'm trying to be API independant, so I shy away from Win32 native code.

Oliii: Thanks. I'll port that to my engine and give you credit.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.