Best place to handle collisions

Hi guys,

I am currently making a Mario clone in order to grasp the concept of building the tech to handle a platformer game (the engine and physics are where I get my kicks).

I have reached a point in the game design where I have now realised that the way in which I handle collisions is not ideal. I’ll explain my process briefly:

  • I have a “Level1” gamestate class where I create a tile map and the entities (the player and enemies).
  • The entities take a reference to the tile map in their constructor.

Each update:

  • The entities calculate their next position based on velocity and handle their own tile map collisions.
  • The collisions between entities (enemy-to-enemy and player-to-enemy) are handled in the PlayState class.

This works just fine, but the issue is that when I create a new level, I will be copy pasting the collision code for the entities, this smells to me like the entity collisions might be better off being handled within the entity class somehow as well but I can’t quite grasp how this would be done efficiently…

How do you guys handle the various collision types in your games (those of you who do your own )?

Why do you have a class for level 1? Each level should just be data.

OK, so maybe a text file should be loaded with enemy positions and then like?

Where do you learn these kinds of things? I find that most learning resources like books are generally aimed at beginners and only cover examples of single level games or gameworlds that are as big as the screen. I’d really like to read something that focuses on intermediate aspects like handling collisions between many different entity groups.

Edit: or might it perhaps be a better learning experience to start looking at other people’s game source code?

The basic rule is to never write the same code twice. If you need to do this it is a clear indication that you should move the logic into a separate method or class, or (if you are repeating code to build objects) you need to separate the data from the code.

“Best Place” ?

before you update, so you know the state of dynamic entities before they act. (If they are blocked, don’t perform ai/player input before checking if they are blocked; in this case you wouldn’t be able to tell yet)

Only check collision with entities that move.

You ‘can’ have a list or data structure that holds a group of nearby solid entities, refreshing this every time the entity moves an increment in some direction. (If tiles are 10 units long, doesn’t have to be pixels, imaginary units, then if the entity moves over a multiple of 10 boundary, refresh the data.)
That would be for tiles though.

For other entities, you could use a quadtree or something to keep track of them.