Good Object Oriented Class Design for collision detection in game development

null picture null · Apr 11, 2012 · Viewed 7.3k times · Source

I want to learn how to create good object-oriented (OO) design practice for collision between two objects situation in game development.

Let's say I have a SpaceShip class and a Meteor class. When Meteor collide with the SpaceShip, the SpaceShip will be destroyed.

The question: What class should I put the method to check if there is collision between meteor and spaceship as well as the collision resolution method (destroy the spaceship)? Is it at SpaceShip class or Meteor class? Or maybe I should put at another class, ie. GameArea or GameController class?

Note: for the sake of simplicity, assume the Meteor and SpaceShip is in form of image resource. I'm used to use Java language, but other language is okay too.

Answer

user1502505 picture user1502505 · Jul 4, 2012

It's more natural to think that collision detection is a responsibility which does not belong to Spaceship or Meteor classes. Especially when this gets complicated with multiple collision possibilities in different directions. If you put this logic in both these classes they will need to have references to lots of other objects that are around them which wouldn't be appropriate.

You could have this on a separate class such as CollisionDetector which keeps track of coordinates of all objects in game space and detect collisions. Collision prevention also appears to be a separate responsibility that should be in a different class in my opinion. You could have a separate class CollisionResolver for this. Depending on the requirements, CollisionDetector could talk to CollisionResolver.

CollisionResolver may need to be able to talk to Spaceships, for purposes such as advising them to change direction, or to command firing missiles towards the Meteor.

CollisionDetector and CollisionResolver could sit within the GameSpace/*GameController*. etc..

This would promote Single Responsibility Principle so each component would be doing only one focussed task.