Re: Double Dispatch Problem: Mobile Creatures and Projectiles in a Game World



"Aaron J. M." <ajmacd@xxxxxxxxxxxxxxx> wrote:

I'm designing a game, and I've come across a problem that's similar
to the one listed here (Google Groups):
http://groups.google.ca/group/comp.object/browse_thread/thread/
4a5c70e3560388c 8

I have a World, and in this world are Creatures and Projectiles.
Both of these have a location, are able to move around somehow, and
can collide with each other. Creatures also create Projectiles
which get added to the World.

For that reason I thought about having both of them be subclasses of
a class Mobile. In addition to sharing behavior, Mobile is
convenient because the World only has to keep one big list of
Mobiles instead of a list of Creatures and a list of Projectiles.

1 N 1
World --------> Mobile <----\
has A 1| | collides with
| \------/
|
/----------^----------\
| |
| 1 N |
Creature -----------> Projectile
shoots
(Did Google Groups take away the fixed width font option?)

The problem is when Mobiles try to collide with each other. Two
Projectiles colliding doesn't do anything (they pass over each
other) and neither does two Creatures colliding (they don't move).
It's only when a Creature and a Projectile collide that something
interesting happens (the Creature is hit). I couldn't really do that
with Mobile without either double dispatch or the Visitor pattern.

To avoid that problem I can just have World hold two lists: one of
Creatures and one of Projectile. But...then I'd need two lists.
That might not be a bad thing, but it is something extra the World
has to take into account and I'm also lazy.

What do people here think about this?

I don't think there is a "lazy" solution, you need two lists. Here's a
possible solution:

World<---Mobile

class World
+reportCreaturePostion( Point )
+reportProjectilePosition( Point )
+creatureAt( Point ): boolean
+projectileAt( Point ): boolean

class Mobile
+attachTo( World )

Mobiles tell the world where they are, and ask the world if there are
any creatures or projectiles at that location. If there are, the mobile
does what it knows it should do.
.



Relevant Pages