I have following classes:
Collider (abstract based class)
BoxCollider
MeshCollider
SphereCollider
The last 3 inherit from Collider.
The use case is that it should be possible for each collider to check if it collides with any of the other colliders.
I imagine the call should be in the Collider class and look like:
void Collider::checkCollisionsWithOtherColliders()
{
for(std::vector<Collider*>::iterator it ....)
{
if(this->isCollidingWith(*it){...}
}
}
Now comes the problem how I should define isCollidingWith
I guess I'd need to define it for each pair of colliders, which means each collider type should have a version of this method for each type of collider as argument, e.g. in SphereCollider:
class SphereCollider : public Collider
{
bool isCollidingWith(SphereCollider* c){..}
bool isCollidingWith(BoxCollider* c){..}
bool isCollidingWith(MeshCollider* c){..}
};
To make sure such methods are accessible thru the Collider base class, I'd need to define
class Collider
{
virtual bool isCollidingWith(SphereCollider* c){..}
virtual bool isCollidingWith(BoxCollider* c){..}
.. and so on
};
Also, since a call this->isCollidingWith(*it) takes just a pointer to Collider and NOT a derived class, I'd wish that the appropriate method of those virtual ones listed is taken automatically in runtime. However, this seems to be not the case: since the parameter is just Collider, it looks for a method with just Collider* parameter.
The only solution I can think of is to define in Collider:
bool isCollidingWith(Collider* collider)
{
if (0 != dynamic_cast<SphereCollider*>(collider))
return isCollidingWith(dynamic_cast<SphereCollider*>(collider));
else if (0 != dynamic_cast<BoxCollider*>(collider))
return isCollidingWith(dynamic_cast<BoxCollider*>(collider));
else if ...
}
which is not really elegant. Is there any other (proper) way to handle such situations? Thanks!
This is a case for double dispatch. Won't detail it here since it's an already widely used idiom and even if the wikipedia page become obsolete, a simple google search with the term would yield a good result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With