Designing and Developing 2D Game Levels with Unity and C#

graceacupuncture - 23/01/2022 - STRATEGY - 653 Views

#Using the Unity Tilemap Editor to Draw 2D Game Levels

There are many ways to create a level for a game, but as previouslymentioned, we're going to be using tilemaps. Unity makes this easy forus because the software provides a paint-like experience where we candraw tiles on the canvas using any available images that we load intothe project.

For this example, we're going to use the following texture sheet:

Rather than creating a new project and repeating previously explainedsteps, we're going to continue where we left off from the previoustutorial.The doordash-level.png file should be placed in theAssets/Textures directory of the project.

While we won't be exploring animations in this particular tutorial, ifyou want the spritesheet used in the animated image, you can download itbelow:

The plummie.png file should be added to the project'sAssets/Textures directory. To learn how to animate the spritesheet,take a look at a previoustutorialI wrote on the topic.

Inside the Unity editor, click on the doordash-level.png file thatwas added. We're going to want to do a few things before we can workwith each tile as independent images.

Change the sprite mode to Multiple.

Define the actual Pixels Per Unit of the tiles in the texturepacked image.

Split the tiles using the Sprite Editor.

In the above image, you might notice that the Pixels Per Unit valueis 255 while the actual tiles are 256. By defining the tiles asone pixel smaller, we're attempting to remove any border between thetile images that might make the level look weird due to padding.

When using the Sprite Editor, make sure to slice the image by thecell size using the correct width and height dimensions of the tiles. Forclarity, the tiles that I attached are 256x256 in resolution.

If you plan to use the spritesheet for the Plummie character, make sureto repeat the same steps for that spritesheet as well. It is importantwe have access to the individual images in a spritesheet rather thantreating all the images as one single image.

With the images ready for use, let's focus on drawing the level.

Within the Unity menu, choose Component -> Tilemap -> Tilemap to adda new tilemap and parent grid object to the scene. To get the bestresults, we're going to want to layer multiple tilemaps on our scene.Right click on the Grid object in the scene and choose 2D Object-> Tilemap. You'll want three tilemaps in total for this particularexample.

We want multiple tilemap layers because it will add depth to the sceneand more control. For example, one layer will represent the furthestpart of our background, maybe dirt or floors. Another layer willrepresent any kind of decoration that will sit on top of the floors — say,for example, arrows. Then, the final tilemap layer might represent ourwalls or obstacles.

To make sure the layers get rendered in the correct order, the TilemapRenderer for each tilemap should have a properly defined SortingLayer. If continuing from the previous tutorial, you'll remember wehad created a Background layer and a GameObject layer. These canbe used, or you can continue to create and assign more. Just rememberthat the render order of the sorting layers is top to bottom, theopposite of what you'd experience in photo editing software like AdobePhotoshop.

The next step is to open the Tile Palette window within Unity. Fromthe menu, choose Window -> 2D -> Tile Palette. The palette will beempty to start, but you'll want to drag your images either one at a timeor multiple at a time into the window.

With images in the tile palette, they can be drawn on the scene likepainting on a canvas. First click on the tile image you want to use andthen choose the painting tool you want to use. You can paint on atile-by-tile basis or paint multiple tiles at a time.

It is important that you have the proper Active Tilemap selectedwhen drawing your tiles. This is important because of the order thateach tile renders and any collision boundaries we add later.

Take a look at the following possible result:

Remember, we're designing a level, so this means that your tiles canexceed the view of the camera. Use your tiles to make your level as bigand extravagant as you'd like.

Assuming we kept the same logic from the previous tutorial, GettingStarted with Unity for Creating a 2DGame,we can move our player around in the level, but the player can exceedthe screen. The player may still be a white box or the Plummie spritedepending on what you've chosen to do. Regardless, we want to make sureour layer that represents the boundaries acts as a boundary withcollision.

#Adding Collision Boundaries to Specific Tiles and Regions on a Level

Adding collision boundaries to tiles in a tilemap is quite easy anddoesn't require more than a few clicks.

Select the tilemap that represents our walls or boundaries and choose toAdd Component in the inspector. You'll want to add both a TilemapCollider 2D as well as a Rigidbody 2D. The Body Type of theRigidbody 2D should be static so that gravity and other physics-relatedevents are not applied.

After doing these short steps, the player should no longer be able to gobeyond the tiles for this layer.

We can improve things!

Right now, every tile that is part of our tilemap with the TilemapCollider 2D and Rigidbody 2D component has a full collision areaaround the tile. This is true even if the tiles are adjacent and partsof the tile can never be reached by the player. Imagine having fourtiles creating a large square. Of the possible 16 collision regions,only eight can ever be interacted with. We're going to change this, whichwill greatly improve performance.

On the tilemap with the Tilemap Collider 2D and Rigidbody 2Dcomponents, add a Composite Collider 2D component. After adding,enable the Used By Composite field in the Tilemap Collider 2Dcomponent.

Just like that, there are fewer regions that are tracking collisions,which will boost performance.

#Following the Player While Traversing the 2D Game Level using C#

As of right now, we have our player, which might be a Plummie or might bea white pixel, and we have our carefully crafted level made from tiles.The problem is that our camera can only fit so much into view, whichprobably isn't the full scope of our level.

What we can do as part of the gameplay experience is have the camerafollow the player as it traverses the level. We can do this with C#.

Select the Main Camera within the current scene. We're going to wantto add a new script component.

Within the C# script that you'll need to attach, include the followingcode:

1using System.Collections;2using System.Collections.Generic;3using UnityEngine;45public class CameraPosition : MonoBehaviour6{78 public Transform player;910 void Start() {}1112 void Update()13 {14transform.position = new Vector3(player.position.x, 0, -10);15 }16}

In the above code, we are looking at the transform of another unrelatedgame object. We'll attach that game object in just a moment. Every timethe frame updates, the position of the camera is updated to match theposition of the player in the x-axis. In this example, we are fixing they-axis and z-axis so we are only following the player in the left andright direction. Depending on how you've created your level, this mightneed to change.

Remember, this script should be attached to the Main Camera orwhatever your camera is for the scene.

Remember the player variable in the script? You'll find it in theinspector for the camera. Drag your player object from the projecthierarchy into this field and that will be the object that is followedby the camera.

Running the game will result in the camera being centered on the player.As the player moves through the tilemap level, so will the camera. Ifthe player tries to collide with any of the tiles that have collisionboundaries, motion will stop.