Thursday, December 15, 2011

How to make a 2d platform game – part 2 collision detection

Hello and welcome back to my blog!

In this series of articles, I’m talking about the technology behind a platform game.

If you missed part 1 you can check it out here.

The language is actionscript 3.0, but the techniques are applicable to all languages.

In this particular article I’m going to talk about the physics, collision detection and AI aspects of the game.

2d platform game

The Game

There is a playable version at the bottom of the post, for those with Flash support in browser.

Class hierarchy

It makes sense at this point to talk about the class hierarchy I’ve used in the game, to represent everything which moves:

Class hierachy

Figure 1

Figure 1 shows the class hierarchy – at the very top sits MoveableObject, which is where all the generic collision detection and response gets done; I say generic because the player does specialised work to handle things like ladders etc.

Each level in the hierarchy represents separate functionality; for example, Character contains the AnimationController which handles playing the various different animations for each character, SimpleEnemy represents a certain class of enemy character which does no collision detection with the world, and obeys special position markers when it encounters them. The Diamond pickup is a simple object which has no AI, and just collides with the world, so it inherits from the base class, since that’s all the functionality it needs.

This may seem like a lot of extra complexity for such a simple game, but it really makes adding new enemy types very easy indeed, and simplifies the debugging process because there is so much code shared between each object.

If I had to give one piece of advice from 10 years of game development it would be this: avoid code duplication at all costs. It leads to slow development and bug city whereby you fix a bug in one location, and then forget to fix it in the other duplicated locations.

MoveableObject has certain properties which it requires be implemented by any class which inherits from it:

  • m_HasWorldCollision – whether full collision detection should be performed
  • m_ApplyGravity – whether gravity should be applied
  • m_ApplyFriction – whether the world collision should apply friction

That way, and child class can chose what elements of collision detection it wants enabled.

Consider the following snippet from the Skeleton character:

Read more: How to make a 2d platform game – part 2 collision detection

No comments:

Post a Comment