How to organize collision detection?

Started by
4 comments, last by yaustar 14 years, 5 months ago
I am currently working on a 2d platformer, but I am at a loss as to how to manage collision detection. If you have a bunch of objects, each of which wants to respond only to collisions with certain other types of objects, how do you decide which pairs to test? The only thing I can think of is to give each object two bool vectors. One vector to hold the attributes that it is, another to hold the attributes it is looking for. Then for every single pair of objects, iterate through the vectors to look for matches, and if any are found, do a collision test. Then if they did collide, have each object iterate through the vectors again to decide how to respond to the collision. This doesn't seem very efficient. Are there any better ways?
I trust exceptions about as far as I can throw them.
Advertisement
Can an object have more then one attribute?

Steven Yau
[Blog] [Portfolio]

Yes

For example, bullets are both Bullet and Deadly. Fireballs are both Flaming and Deadly.

Those attributes are not set in stone (or anything for that matter), but I can't really think of a good way to do things with a single attribute per object.

The player character is interested in collisions with anything that is a platform or deadly. Bullets are interested in anything that stops bullets or is shootable. Flamable objects are interested in anything that is flaming. Falling objects are interested in platforms. Monsters are interested in bullets and explosions. Trigger regions are interested in the player character.
And those are just the types of objects that are in the level I already designed.
I trust exceptions about as far as I can throw them.
Bitfields with bitmasking seems to be the way to go. Example:

namespace Attributes{	enum eAttributes	{		PLAYER = 1,		BULLET = 2,		ENEMY = 4,		WORLD = 8,		JUMPABLE = 16,		};}struct Object{	Attributes::eAttributes mAttributes;	Attributes::eAttributes mCollideWithFilter;	};Object player;player.mAttributes = Attributes::PLAYER | Attributes::JUMPABLE;player.mCollideWithFilter = Attributes::BULLET | Attributes::ENEMY | Attributes::WORLD;Object enemy;enemy.mAttributes = Attributes::ENEMY;enemy.mCollideWithFilter = Attributes::PLAYER | Attributes::WORLD;if( enemy.mAttributes & player.mCollideWithFilter ){	// Player collides with enemy}


The flaw with this is that you can set the player to collide with the enemy and set the enemy NOT to collide with the player if the attributes are set up incorrectly. However, this is easy to sanity check via an automated code test.

Steven Yau
[Blog] [Portfolio]

I guess that's the best approach. It does limit things to 32 attributes, but I can't think of any reason I'd actually need that many.
I trust exceptions about as far as I can throw them.
The C++ Bitset class might be able to handle more then 32 bits.

Steven Yau
[Blog] [Portfolio]

This topic is closed to new replies.

Advertisement