Spacefight – The game-loop – Part 6

An example of a game loop

An example of a game loop

All games contain loops of some sort. The most important loop in the game is simply called “game-loop”. This is a short example how it will run:

This is a short version of what is happening in the code. It sets up the gameObjectList vector and adds new game objects into it. It also iterates through the vector once to initialize the objects. If a new object type hasn’t been loaded before it needs to load graphics and maybe sound. The gameobject does that via the init().

The game loop is usually a while loop. We create a boolean that indicates that the game is running, and therefore the gameIsRunning boolean is true.

Let’s go through the game loop step by step:

  • First in the loop it checks whether the user is quitting, it checks for the input via SDL_Event and SDL_PollEvent. If quit has been catched it will set gameIsRunning to false.
  • Remeber we talked about the depth variable zIndex. I call a sort function that places the objects with the lowest zIndex first in the vector and the highest lasts. This way it will be correctly layered on the screen.
  • Now when the list is sorted it’s time to go through all the objects:
    • listen(event, gameObjectList), catches the event and passes it along to the object.
    • update(gameObjectList), updates the position and other stuff.
    • draw(screen), passed the screen, which is the screen surface, and adds graphics to that
  • The collision detect function is called. This is checking for objects that are colliding and informing the objects which object(s) they are colliding with via handleCollision(listOfObjectsICollideWith).
  • Next I go through the gameList again and remove the objects that are marked for termination. This is a bit tricky since the objects aren’t really objects but pointers to new’d objects. Hence they’ll need to be deleted, and the element in the vector needs to be erased which isn’t super trivial. The game will crash if it’s not cleaned up properly. Luckily I found this answer on stackoverflow that helped me out. It’s also in this code block I check whether the player is dead -> quit the loop or no enemies left -> quit the loop.
  • Lastly I update the screen with SDL_Flip. And I call a delay to limit the framerate. This is important for two reasons. If no limit is set the CPU will go up to 100% running in your game-loop, and second the game will run in different speeds on different machines.

Already now I see there’s room for structural improvements, but I’ll wait with that until the next project. Since this game is meant to be fairly simple in structure.

Posted in Game programming Tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *