0

Let's say I have two different types of colliders, circles and boxes, that are derived from the same base collider class. I have an entity class that contains a pointer to a collider that can be a circle collider or a box collider.

class Collider {};

class CircleCollider : public Collider
{
    // Defines a circle
};
class BoxCollider : public Collider
{
    // Defines a rectangle
};

class Entity
{
    Collider* collider;
};

I want to make a collision handler that I can just pass a bunch of entities and let it figure out how to resolve their collisions but in order to do that the handler needs to know what types of colliders it is dealing with.

When the problem is framed liked this, the only solution appears to be downcasting but I am wondering whether I am simply approaching it the wrong way. This seems like a common scenario but I am having trouble finding solutions which makes me suspect that either there is some other approach that I am not seeing or that this is a case where one simply has to make use of downcasting.

Since the collision handling is specific to different pairs of colliders, it doesn't seem like I can make use of the visitor pattern here or am I wrong?

  • 1
    Sounds like textbook double dispatch - see http://en.wikipedia.org/wiki/Double_dispatch#Double_dispatch_in_C.2B.2B – Tony Delroy Apr 01 '14 at 04:43
  • see [Double dispatch](http://en.wikipedia.org/wiki/Double_dispatch) if you need different behaviours by each pair of objects. If it doesn't matter what each object collides with, the solution below @Straw1239 is fine. – jsantander Apr 01 '14 at 04:43
  • Double dispatch looks like what I was looking for but did not know the name of, thank you. – Freegor Apr 01 '14 at 05:00

1 Answers1

1

If you added a virtual method collidesWith(Collider c) to the Collider class, and added specific implementation in BoxCollider and CircleCollider, which would figure out if those particular instances collided, an external collision handler would never have to downcast or even know what specific type of collider it was using.

Straw1239
  • 589
  • 2
  • 8
  • My initial thought was to solve it along those lines but you still need to know the type of both colliders to resolve the collision which would require downcasting the passed collider in this case. It seems like asking each type of collider to know about all others is less efficient than having the handler do that. Or am I missing something? – Freegor Apr 01 '14 at 04:57