Simple Procedural Level Generation In Unity
Like this post? You might like BentoBlox too — check out the game here on the App Store.
This week I’m continuing to prototype the 2D vertical platformer I began working on earlier in the month.
The game mechanic is a classic, uncomplicated one (go play the originalNES
Ice Climber title — that’s essentially what I’m aiming to recreate). The player makes “progress” by moving upward through space, jumping from one platform to another.
One way to approach level generation for this game is to write a script that generates all platforms at once. But doing so limits the scope of the game. I opted instead for a simple procedural implementation that generates platforms as needed during gameplay as the player moves upward through space.
The approach is simple and consists of 3 components:
- A
Platform Spawner
game object - A
Platform Collector
game object - A
Platform
prefab
The idea is that both the Platform Spawner
and Platform Collector
move with the main camera, the Platform Collector
telling the Platform Spawner
to generate a new platform each time it comes into contact with an existingPlatform
as it moves upward following the player’s progress.
To accomplish this, I add both as child objects of the Main Camera. The Platform Spawner
is positioned above the main camera’s viewport, while the Platform Collector
is positioned below. To ensure that the Platform Collector
collides with Platform
s positioned at random horizontal positions, I add aBoxCollider2D
component and extend it horizontally in both directions.
The Platform
prefab is simple: just a GameObject
with BoxCollider2D
and Sprite Renderer
components attached:
I also create and add a “Platform” tag to the Platform
prefab, which will come into play shortly.
The Platform Spawner
's role is to generate an initial set of platforms, and then generate an additional platform whenever the Platform Collector
comes into contact with a Platform
as the camera follows the player’s progress and moves upward.
The logic for this lives in a few small scripts (find them here, here, and here) attached to the Platform Spawner
and Platform Collector
game objects respectively.
The Platform Collector
script consists of a simple check in the OnTriggerEnter2D
method. If the collider it comes into contact with is tagged as a Platform
, it calls a method on the Platform Spawner
to position a new Platform
.
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == Constants.platformTag)
{
PlatformSpawner.Instance.PositionNewPlatform();
}
}
This week, time permitting, I’ll be adding a few things to round out the basic gameplay (obstacles, a “boss”, we’ll see). In the meantime I’d love any feedback, suggestions, or thoughts you might have about this post.
Like this post? You might like BentoBlox too — check out the game here on the App Store.