# 2D Collision Detection with Multiple Objects

#### slinga

##### Established Member
Hi all,

I'm chugging along on my contest entry and I'm still stuck on how to do 2d collision detection with multiple objects. My game objects include players (1-12), enemies (0-10?), obstacles (0-5?), and ground (1-10?). All objects are using rectangular bounding boxes.I have AABB collision detection implemented for my objects.

I'm struggling with some of the more advanced stuff:
- how do I handle collision detection with two moving objects?
- what happens if two objects pass each other in a frame and are no longer hitting?
- how do I determine which direction the objects hit each other from? Sounds easy but if the objects pass through each other it's harder

I'm also not clear on how my gameplay loop should look like. Assuming I have 3 functions input(), updateState(), and draw() called per gameplay frame. Do I read inputs from all players first before calling updating? Do I check input and update each object at a time?

Reyme mentioned SweeptAABB which looks interesting but appears that it's designed for the case one object is moving and the other is stationary. I can implement that for object vs ground collisions.

#### Knight0fDragon

Patron Supporter
Moving objects are a little more complex.
Instead of AABB. you can do line intersect tests using pre movement and post movement data on each vertex. Basically, you are making it into a long box, and checking if 2 long boxes collide.

You can then take this one step further.

The intersection points will tell you how far along you are in time.

If you were to normalize the line (make it go 0 to 1), the intersection point becomes a percentage. You can then apply that percentage to the object you collide with, and check to see if AABB collide.

You should only be doing this for things of super fast speed like bullets.

#### DamageX

Compare the difference between old and new coordinates (ie. the distance travelled in one frame) with the size of the hitbox. If the hitbox is bigger then the sprite can't 'skip over' another sprite, so only test one set of coordinates for a collision. If the hitbox is smaller than the distance travelled, you can choose intermediate point(s) in between the old and new coordinates and test for a collision there also.

#### slinga

##### Established Member
I watched this video and it helped: .

The main thing I was missing was storing the previous position every frame.

#### CheoChessman

There is always an easy mode to do things if you know how

Replies
87
Views
22K
Replies
0
Views
871
Replies
12
Views
2K
Replies
2
Views
725
Replies
74
Views
20K