Sometimes in an arcade game where you have different types of entities, the most difficult part is to resolve the collision. Nope, the issue is not detecting collision (which is already one big headache by itself), but rather – “So something did collide; so what’s next?”
There are two questions to this:
- Who hit me?
- Knowing who hit me, what do I do next?
Of course, you could use RTTI to figure that out and resolve that (here’s an article on RTTI). However, for those who prefer not to, you can use the visitor pattern as described in a previous post on double dispatch to implement this. Here is a C# sample which you can download to see how it works. There will be more coming later on how it works and some pitfalls to look out for. You can download the C# Sample of the Vistior Pattern from this link.
Double Dispatch?
Here’s the “un-computer science” explanation of double dispatch. C++ and C# are languages which support polymorphic functions (or virtual functions). This means that methods (or member functions, according to C++) are resolved at the run-time at object level. This is the basic premise of polymorphism (you can find more details at DotNetUncle).
The issue is that there is no polymorphism at the function signature level; this means that suppose you have an abstract class called Entity. You have a whole hierarchy of objects, such as Missile, Asteriod and Ship. If you have a function which says have the signature CollideWith(Entity e), and the various variants – CollideWith(Asteriod a), CollideWith(Ship s) and CollideWith(Missile m), CollideWith(Entity e) would always be called if you do not cast the object to the child. (Sucky explanation, I know. I’ll try to come up with a detailed example).
Other readings
Other places on the Internet has grappled with resolving collision resolving in an OO manner too, such as this forum post on a GameDev.Net forum.

This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Singapore License.












