# Abstracting Collision without RTTI?

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

## Recommended Posts

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?

##### Share on other sites
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.

##### Share on other sites
An alternative is the double dispatch idiom.

##### Share on other sites
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]

##### Share on other sites
double dispatch or a look up table of functions, and typing your collision primitives. Bit like your own RTTI.

##### Share on other sites
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.)

1. 1
2. 2
Rutin
22
3. 3
4. 4
5. 5
frob
12

• 17
• 9
• 31
• 16
• 9
• ### Forum Statistics

• Total Topics
632615
• Total Posts
3007441

×