Public Group

# question about collision detection, from an idiot

This topic is 4573 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have finished a couple of semesters in C++ in school and was looking to improve my programming skills. So I have started studing SDL using the LazyFoo tutorials. On lesson 13 I came across a problem that demonstrated basic Collision Detection. It was very similar to the example given on this site.

// Object-to-object bounding-box collision detector:
short int Sprite_Collide(sprite_ptr object1, sprite_ptr object2) {

int left1, left2;
int right1, right2;
int top1, top2;
int bottom1, bottom2;

left1 = object1->x;
left2 = object2->x;
right1 = object1->x + object1->width;
right2 = object2->x + object2->width;
top1 = object1->y;
top2 = object2->y;
bottom1 = object1->y + object1->height;
bottom2 = object2->y + object2->height;

if (bottom1 < top2) return(0);
if (top1 > bottom2) return(0);

if (right1 < left2) return(0);
if (left1 > right2) return(0);

return(1);

};


I don't understand why this works. I know that it does and am not trying to argue against people that obviously know more than me. My problem is that I don't get why it wouldn't return(0) anytime (bottom1 < top2) if they are touching or not. for instance

__________________
|                  |
____________             |                  |
|            |         2        |
|            |                  |
1       |            |                  |
|            |__________________|
____________|


in this example the bottom of 1 is less than the top of 2 so it should return(0).


_____________
|             |
__________|_            |
| |     2     |
1    | |           |
|_|___________|
____________|


in this example the bottom of 1 is less than the top of 2 so it should also return(0). What am I missing?

##### Share on other sites
Those are test to see if there could be any intersection between two rectangle. Take for example bottom1 < top2. This means that if the bottom of rectangle 1 is above the top of rectangle 2, then they can never intersect. The same applies to the other three tests (if left1 > right2, then the box is located completely to the right side of rectangle 2, etc).

##### Share on other sites
It looks like in your code, positive Y is in the downward direction. So the 'bottom1 < top2' test case would actually look like this:

0 ******
1 * 1 **
2 ****** <-- bottom1
3     ******* <-- top2
4     ** 2 **
5     *******

Down the left I wrote the 'y' coords for these positions. As you can see, these boxes don't collide. Bottom1 = 2 and top2 = 3. Bottom1 < top2 is 2 < 3 which is true, so they can't possibly collide.

##### Share on other sites
Thank you both, that makes sense.

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 26
• 11
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633702
• Total Posts
3013450
×