Friday, May 09, 2008

Multiple Dispatch

Specifying collision detection logic for scenarios in games that have an inheritance hierarchy for game objects will usually lead to a code for handling the collision event. In this case, if the code happens to be polymorphic, then we will encounter code that will look something like "gameObjectA->handleCollision(gameObjectB)". The two game objects are probably just base class pointers to sub class objects and we usually need different handling code for when different object types collide. An arrow hitting an enemy needs different handling than the arrow hitting a tree.

Now in a single dispatch language such as C++, the above code will have trouble finding out how exactly to handle the event since different handlers can not be selected at run time based on the real type of gameObjectB. ( Assuming we have handleCollision(Tree*) and handleCollision(Enemy*) for the Arrow object). Dynamic binding only works using one parameter and in c++ that would mean using virtual methods. At least the double dispatch mechanism is needed for the collision case.

However one technique which can be used for the above scenario and would help out a little is the use of the visitor pattern.

Stroustrup and some of his students are working on an interesting project to add multiple dispatch functionality to the c++ compiler. The paper can be found here. Would be nice to see this feature in standard c++ someday.

No comments: