Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write an elegant collision handling mechanism?
    primarykey
    data
    text
    <p>I'm in a bit of a pickle: say I'm making a simple, 2D, Zelda-like game. When two Objects collide, each should have a resulting action. However, when the main character collides with something, his reaction depends solely on the type of the object with which he collided. If it's a monster, he should bounce back, if it's a wall, nothing should happen, if it's a magical blue box with ribbons, he should heal, etc. (these are just examples).</p> <p>I should also note that BOTH things are part of the collision, that is, collision events should happen for both the character AND the monster, not just one or the other.</p> <p>How would you write code like this? I can think of a number of incredibly inelegant ways, for instance, having virtual functions in the global WorldObject class, to identify attributes - for instance, a GetObjectType() function (returns ints, char*s, anything that identifies the object as Monster, Box, or Wall), then in classes with more attributes, say Monster, there could be more virtual functions, say GetSpecies().</p> <p>However, this becomes annoying to maintain, and leads to a large cascading switch (or If) statement in the collision handler</p> <pre><code>MainCharacter::Handler(Object&amp; obj) { switch(obj.GetType()) { case MONSTER: switch((*(Monster*)&amp;obj)-&gt;GetSpecies()) { case EVILSCARYDOG: ... ... } ... } } </code></pre> <p>There's also the option of using files, and the files would have things like:</p> <pre><code>Object=Monster Species=EvilScaryDog Subspecies=Boss </code></pre> <p>And then the code can retrieve the attributes without the need for virtual functions cluttering everything up. This doesn't solve the cascading If problem, however.</p> <p>And THEN there's the option of having a function for each case, say CollideWall(), CollideMonster(), CollideHealingThingy(). This is personally my least favourite (although they're all far from likeable), because it seems the most cumbersome to maintain.</p> <p>Could somebody please give some insight into more elegant solutions to this problem? Thanks for any and all help!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload