Abstracting Collision without RTTI?

Started by
4 comments, last by Bob Janova 17 years, 1 month ago
Hey all, Is there a way to abstract collision volumes without RTTI? RTTI doesn't seem like the most flexible method, but I can't think of another way to accomplish it. I don't know if it's going to be such a big deal though, since collision bodies are rarely going to change. Here's what I mean:

class Body
{
	virtual bool Collides(Body other);
}

class Rectangle : Body
{
	virtual bool Collides(Body other)
	{
		if(other is Rectangle) {}
		else if(other is Circle) {}
		// etc, for every body.
	}
}

class Circle : Body
{
	virtual bool Collides(Body other)
	{
		if(other is Rectangle) {}
		else if(other is Circle) {}
	}
}
Every time you add a new body, you'll need go in and change every other body. I doubt that'll happen more than once or twice at best, but it's still not the safest of methods. However, tests can be very different between bodies. Stuck between a rock and a hard place... Ideas?
Advertisement
Some ideas:

1) You can calculate an quadtree (in 3D octree= starting from the AABB of each object. Then just check the quadrees of both objects against each other. You can also calculate that structure on the fly to provide any required precision.

2) You can convert the shape of an object to connected lines (in 3D triangles for the surface), then check if the lines intersect.

3) Use a line sweep along one axis and calculate the interval(s) that belong to each object. If intervals overlap, then the objects intersect. This may be useful if the objects are already represented by pixels.

In general you should try to abstract the different shapes in a common way like pointed out above.
An alternative is the double dispatch idiom.
I quite like double dispatch for this kind of thing. You still have the problem of modifying every object when adding a new type, but for collision primatives this isn't much of a problem.

Edit: too slow. [grin]
double dispatch or a look up table of functions, and typing your collision primitives. Bit like your own RTTI.

Everything is better with Metal.

What I do for this is I don't delegate collision detection to the individual objects. Instead I have a single method in the game engine
bool Collision(Primitive[] shape1, Primitive[] shape2){ // a shape has a series of simple collision primitives ...}

... and only have a very limited number of primitive shape types so the n² switch stays small. (For 2D you only need circle, AABB, OBB and poly; for 3D it's the same except arbitrary convex hull not poly.)

This topic is closed to new replies.

Advertisement