Skip to main content

Command Palette

Search for a command to run...

Gaming Spawning System (templates)

Published
2 min readView as Markdown
J

I am a recent grad of Northern Illinois University working on my own projects and now on the hunt for a job!

I'm still a learner: graduating two semesters from this writing. My largest project is a mostly complete (still needs tightening up and some bells and whistles) game called Splonking. It's quite fun and took me a lot of C++ muscle flexing as well as a lot of time. I used the SDL library to handle display, input/output, etc. It's a FANTASTIC library for game usage: I can't recommend it enough.

Here's a quick playthrough of the game.

Depending on when I get the time, I want to extend this project to be a genericized game-making template/library to work with to do simple primarily 2d games. But one of the trickiest bits I did is the spawn checking/spawner function. The code is below for the function, but basically, a type Entity_Data is generated for each individual enemy, pickup, etc. All of the pickups, monsters, etc. are specific classes which inherit from a few generic classes such as entity, mover, controllable, etc. This way, you can use only a few lines of code to check if it's time for one of this entity to spawn, and use the template class so you don't have to write a spawn-checker for each individual type of entity that might spawn. It's quite cool.

template <class T>
void check_for_spawn(unique_ptr<Game_State>& game_state, Entity_Data init)
{
    game_state->ent_handler->decrement_ticks(init.ent_type);
    {
        if (rand() % SPAWN_RATE == 0 && 
            game_state->ent_handler->get_current_on_screen(init.ent_type) < game_state->ent_handler->get_max_on_screen(init.ent_type) && 
            game_state->current_level->get_difficulty_level() >= game_state->ent_handler->get_min_difficulty(init.ent_type) &&
            get_ticks(init.ent_type) <= 0)
        {
            game_state->ent_handler->spawn_new<T>(game_state, init);
            game_state->ent_handler->increment_current_on_screen(init.ent_type);
            game_state->ent_handler->reset_ticks(init.ent_type);
        }
    }

It's quite cool. First, each entity's "ticks" count, which is essentially a countdown ticks down. For each specific entity. Then it checks vs a random factor, whether or not the object is allowed to spawn on screen due to difficulty level or max on screen. If it all checks out, you simply spawn_new<t> which is the type of entity (ghostal, player, fuel pickup, etc) you passed into the template. It increments the count on screen, and reset ticks.

Using the template saves you literally hundreds of lines of redoing these things for each entity, and lets you use a generic spawning function for any entity. Pretty cool stuff!

If you have any other examples of cool template use, feel free to comment. And check out SPLONKING in alpha form on itch.io.