Hi again guys,
Rapid development is an amazing thing, but often I find that it’s easy to get ahead of yourself and glaze over what could potentially become bigger problems in future. Which is why I’d like some fellow developer input on this one
Here’s a screen-grab of a WIP project:
This game is intended have a large number of enemies on the level (not necessarily the screen) at any one time (~300).
From my tests, it seems that the overall game logic time hits about 10ms at the 120 enemy mark. I want to know if my approach is correct, and what optimisations I could possibly make.
Bear in mind that I know I could just stop calculating enemy positions and movement when they’re off screen - but because they spawn from specific locations, it’d be silly to have them spawn and not move anywhere until they’re closer to the player. It’d look like they’ve all just suddenly spawned when the game starts processing their logic.
Here’s my current process:
Every game tick:
-
Cycle through each map tile, calculate the potential collision with the player and the environment (i.e. walls).
-
Within each of these discrete per-tile calls, I cycle through the whole ArrayList of enemies, and once again check whether or not they either collide with that wall - or with the player - and respond accordingly.
So essentially, it’s a loop within a loop. The pseudo-code loop structure looks a bit like this:
int tileIndex = 0;
for (int y = 0; y < GAME_HEIGHT_IN_TILES; y++)
{
for (int x = 0; x < GAME_WIDTH_IN_TILES; x++)
{
// get a reference to this tile
Tile t = tileMap[y][x];
// is this an obstacle?
if (!t.walkable)
{
checkPlayerCollisionWithTile(t);
// run through the enemy arraylist and check their potential to collide with both this obstacle and the player
for (Enemy e : enemyList)
{
checkEnemyCollisionWithPlayer();
checkEnemyCollisionWithTile(t);
}
}
tileIndex++;
}
}
This method feels, I don’t know, a bit ugly I guess. It seems to work perfectly in practice, and to be honest if I wasn’t having so many enemies trackable in the game simultaneously - I may have just conceded this as a hackish method of calculating multiple collision events and pushed on with the rest of the game.
Maybe this is the only tangible way of approaching this problem? After all, each enemy still needs to be tracked off screen and their collisions with the environment honoured, so can I ever escape this?
I’m not a professional game developer, though, and I’m all for learning new tricks and optimisations for these types of scenarios, so I’d be most grateful for some input from fellow developers on this approach.
EDIT: Updated the rather annoying lack of tabs on my code block!