2D Collision Response For CSE 3902 By: Matt Boggus
Collision response organization options Response logic in client code Methods in Mario.cs Response logic encapsulated in dedicated classes MarioCollisionHandler MarioBlockHandler, MarioEnemyHandler, etc. AllCollisionHandler
Separation of concerns: collision detection vs. collision response Assume a collision detection class has already determined the type of collision (ICollision) Left Right Top Bottom None
Response logic in Mario Expect to see methods like: void HandleBlockCollision(Block block, ICollision side) void HandleEnemyCollision(IEnemy enemy, ICollision side) etc. Lowers cohesion and raises coupling of Mario class
Response logic in MarioCollisionHandler Still expect to see methods like: void HandleBlockCollision(Block block, ICollision side) void HandleEnemyCollision(IEnemy enemy, ICollision side) etc., assuming the class has a reference to mario stored in a field Mario class’ cohesion and coupling remains the same as before This class has high coupling
Response logic in MarioBlockCollisionHandler Now only expect to see the method: void HandleCollision(Mario mario, Block block, ICollision side) This class has high cohesion and low coupling That’s good! Similar to the state pattern, we increase the total number of classes and risk code duplication
Selecting the right collision handler Given generic storage, like List<IGameObject> gameObjects Decision making logic is required to determine the correct handler or methods Can we avoid branching statements (if, else, switch)?
AllCollisionHandler Consider a table of use cases
AllCollisionHandler Each use case has a specific response; we can encapsulate methods using Command objects. This makes a Dictionary that we can use for lookup. Note: passing the data needed to carry out these commands is easier said then done.
Relevant design patterns for collision detection and handling Visitor A way of separating an algorithm (handleCollision) from an object structure on which it operates (different types of GameObjects) Observer The subject (the collisionHandler), maintains a list of its dependents, called observers (the GameObjects), and notifies them automatically of any state changes, usually by calling one of their methods.