Generating A Semi-Random 2D Platformer Level
Today, here’s a quick post on how to create semi-random levels for a 2D arena game.
--
Today’s Objective: Create a simple random level generator by randomly selecting from premade section prefabs.
The Design:
First I divide the playable area into 5 sections, since that number suits my needs best for level objects.
Each of these sections will show a different terrain element, randomly chosen on each generation, from an array of premade elements for that section.
The Hierarchy structure looks like this:
The Code:
Now in a new script I’ve called LevelGenerator, I create the array variables to hold all possible section options.
Next it’s the functions, which are pretty simple:
The Section Options:
Now, as for the section options themselves, and how I’ve created them, it’s simple. I’ve chosen to use ProBuilder’s “New Poly Shape” tool to create custom 2D objects:
I’ve created a number of these for each level section (and mirrored many to fit the opposing section). I’ve then placed all of them under their appropriate parent objects in the Hierarchy and disabled them:
My current method is to drag all options for each section into the appropriate array collections manually, but I aim to automate this very soon.
Now whenever the GenerateLevel method is called, each section randomly chooses one of the possibilities and shows that section object (though I’ve made both the top sections, and both the bottom sections show the same (but mirrored) terrain for my game).