Updating entities in response to collisions - should this be in the collision-detection class or in the entity-updater class?

Posted by Prog on Game Development See other posts from Game Development or by Prog
Published on 2014-06-12T20:11:28Z Indexed on 2014/06/12 21:41 UTC
Read the original article Hit count: 176

In a game I'm working on, there's a class responsible for collision detection. It's method detectCollisions(List<Entity> entities) is called from the main gameloop.

The code to update the entities (i.e. where the entities 'act': update their positions, invoke AI, etc) is in a different class, in the method updateEntities(List<Entity> entities). Also called from the gameloop, after the collision detection.

When there's a collision between two entities, usually something needs to be done. For example, zero the velocity of both entities in the collision, or kill one of the entities.

It would be easy to have this code in the CollisionDetector class. E.g. in psuedocode:

for(Entity entityA in entities){
    for(Entity entityB in entities){
        if(collision(entityA, entityB)){
            if(entityA instanceof Robot && entityB instanceof Robot){
                entityA.setVelocity(0,0);
                entityB.setVelocity(0,0);
            }
            if(entityA instanceof Missile || entityB instanceof Missile){
                entityA.die();
                entityB.die();
            }
        }
    }
}

However, I'm not sure if updating the state of entities in response to collision should be the job of CollisionDetector. Maybe it should be the job of EntityUpdater, which runs after the collision detection in the gameloop.

Is it okay to have the code responding to collisions in the collision detection system? Or should the collision detection class only detect collisions, report them to some other class and have that class affect the state of the entities?

© Game Development or respective owner

Related posts about collision-detection

Related posts about game-loop