It’s again time to defend earth against alien invasion with the SDL2 version of the Space Invaders! As previously, I decided to re-implemented my HTML5 version of the game into a SDL2 (C++) application to see how some new important features (like pixel wise collision detection) could be implemented with different technique and environment. The basis of the game is quite similar to the HTML5 version described in HTML5-Space-Invaders.
At the beginning…
Again, it was easy to split the application into reasonable classes as it was already done in the HTML5 version. I did a bit further split with some game elements like alien shots. HTML5 version handled shot specific details directly within the in-game state, which made some unnecessary code bloat to in-game update function. Now I decided to encapsulate those details into shot specific classes so they can be more easily examined.
The game structure was a quite similar than the HTML5 version, but some minor differences that where required by the SDL2 framework. One of the most important change was the way how pixel precise collision detection and pixel re-coloring works.
To edit SDL2 textures, I needed to build a locking structure that locks the texture so it can be edited. After the texture is edited, it must be freed so it can be used by other systems. I somehow managed to get this working by building a quite simple structure that actually seems to work. However, I’m quite sure that my implementation could be better formed so it would split the operation into much more logical steps. Now, the whole shield to laser/missile detection and pixel edit functionality is all included in a single place. This is a quite ugly way to perform it, but I’ll try to accept that…. Perhaps…
This implementation actually took me a much more time that I was expecting. It was quite interesting to note how much easier it is to perform pixel wise collision detection and editing in the HTML5 than in the SDL2 (C++) environment. Luckily, many games do not require this kind of collision detection as we have a quite nice set of all kinds of bounding volumes (e.g. AABBs) that we can use to perform optimized detection without iterating over the whole set of pixels.
Thanks for reading!
Game source code in GitHub: https://github.com/toivjon/sdl2-space-invaders