(I asked a similar question, but this one is far more specific).
How can I handle collisions without having to do a lot of type checking and if
statements?
People here suggested that when spotting a collision, the collision detector should notify both entities in the collision, and the entities themselves will encapsulate the logic to react to the collision.
I like the idea of having the entities themselves decide how to handle the collisions. However I'm not sure how to avoid doing a lot of type checking and if
statements inside the handleCollision
methods.
For example (in psuedocode):
class CollisionDetector{
foreach entity in entities
foreach otherEntity in entities
if(collision(entity,otherEntity)) entity.handleCollision(otherEntity);
}
class Entity{
// .. stuff omitted
void abstract handleCollision();
}
class Alien extends Entity{
// .. stuff omitted
void handleCollision(Entity entity){
// lots of ugly conditionals and type checking
if(entity instanceof Missile) die();
if(entity instanceof Alien) lifePoints -= ((Alien)entity).getDamagePoints();
if(entity instanceof Wall) setVelocity(0,0);
// .. etc
}
}
In OOP we should try to avoid type checking and employ Polymorphism. But I don't see how this can be done in this case.
Is there a way to avoid the ugly type checking and lots of conditionals? Or should I just make my peace with it? How is this most commonly done?
No comments:
Post a Comment