Quantcast
Channel: GameDev Academy
Viewing all articles
Browse latest Browse all 1620

How to Build a Complete 2D Platformer in Unity

$
0
0

Introduction

Since the release of Unity 2017.1 in the summer of 2017, Unity Technologies has made making 2D games incredibly easy and fast. In this tutorial, we will create a fully-featured 2D platformer. This project will incorporate a number of key topics including how to make cutscenes, how to quickly build and prototype a 2D level, and how to precisely choreograph game objects using the Timeline Editor. This tutorial can also be thought of as the culmination of several tutorials – posted on Game Dev Academy – about these topics. You can check them out here:

Storytelling in Unity – Part 1: Virtual Cameras

Storytelling in Unity – Part 2: Animation Tracks

Cinemachine and Timeline Editor for Unity 2D Game Development

Mastering Unity’s New Tilemap Editor: Building 2D Levels

Project Details

Let’s think about what we will be making. As said in the introduction, it will be a 2D platformer. We will use the 2D character from the Unity Standard Assets pack. Then we will create an environment using tilemaps and Unity’s new Tilemap Editor. Then we will create an enemy that has an Idle/Attack animation (you’ll see). Then we will create a cutscene where the camera views the entire level then zooms on the character: here we will use the Timeline Editorand Cinemachine for 2D.

Tilemap Editor, Timeline, and Cinemachine

When Unity Technologies released the Unity 2017 version cycle, they introduced three pivotal tools designed to make Unity more accessible to artists. These tools were the Tilemap Editor, Timeline, and Cinemachine. The Tilemap Editor, released later in the 2017 cycle, allowed users to “…literally paint directly in Unity” according to Rus Scammell, the project manager of Unity for 2D. The Tilemap Editor gives you the ability to create vast and complicated Tilemaps without having to use a third-party program. The Timeline Editor and Cinemachine were released at the same time, though improvements to Cinemachine were released later. Cinemachine is a suite of cameras that allows you to create cutscenes, specify how the camera tracks a game object, and, in the end, allows you to tell a better story. Combine this with the Timeline Editor, a tool that allows you to choreograph game objects like a movie editor. With these two tools, you can create stunning compositions with having to write any code. Well, that’s a summary of the tools that we will be using! This tutorial is by no means exhaustive, for more information about these tools check out the tutorials linked above.

Setting up our project

The assets for this project you can get here. Then create a new Unity project. Let’s import the 2D Standard Assets package by going to Assets -> Import Package -> 2D.

Unity Assets menu with Import Package 2D selected

Next, we need to create two new folders. One called “Animations” and the other called “Tiles”.

Assets folder with Animations, Standard Assets, and Tiles folder

In the Tiles folder, create another folder called “Tile Palettes”.

TilePalettes folder within the Tiles folder of the Assets

The use of this folder will become apparent later on. Now let’s import Cinemachine by going to the asset store and searching “Cinemachine”. It should be the first option so just select it and import it.

Unity Asset Store with CineMachine highlighted

Now we need to import the Tilemap Editor tools. Click this link to take you to the Github download page. Import this into the “Assets” folder of your project.

Assets folder with the addition of 2d-extras-master folder

Now that we have everything imported we can start getting our tools in order. We will start with the Tilemap Editor. Go to Window -> Tile Palette.

Window menu with Tile Palette selected

Place it in a sensible place on your workspace. I chose to put it in the space between the inspector and the scene view. Next, we need the Timeline Editor. Go to Window -> Timeline Editor.

Unity Window menu with Timeline selected

The position of this tab is not set in stone so be prepared to move it around. We now have our workspace in order! Time to start creating!

Creating our environment

Go to your Tile Palette tab and create a new palette. Call it “Solids” since these are the tiles that the character will not be able to pass through.

Tile Palette with Create New Palette window open

A palette works just like you would expect it to based on the name, it is a set of images that we use to “paint” with. Leave all of the settings set to default and save it in the Tile Palettes folder which we created in the Tiles folder.

Solids tile palette within the TilePalettes folder

Now, go to your “Environment Tiles” folder and pick out a set of environment tile images. Once you have selected an environment theme, select all of them and change the Pixels Per Unit value in the import settings.

Tiles in Unity with 126 set to the Pixels Per Unit

The reason we do this is so that the tile images correctly fit the tile cells in the grid space. Click “Apply” and your good to go! Next, we are going to create a special type of tile, called a “Rule Tile”, that will drastically speed up level creation. In the Tiles folder, right click and go to Create -> Rule Tile.

Unity Create menu with Rule Tile selected

Name it “Environment Tiles”.

Environment Tiles as they appear in the Tile folder

We have to do one last thing to our tile images and that is to make them into Tiles instead of just images. The easiest way to do this is to drag all of the environment images into the Tile Palette tab.

PNG Grass tiles added to the Tile Palette

You will be asked where to save each tile. This can be kind of tedious so just get through it as fast possible and save each tile in the Tiles folder. Now go to your rule tile and create a place for each of your environment tiles. The settings for this rule tile can be kind of complicated and hard to get used to. That is why it is best if you just copy the settings of this rule tile:

Environment tile rule settings

Once you are finished, drag your rule tile into the Tile Palette tab.

Rule tile dragged onto current Tile Palette

Now that all of our tiles are in order, let’s create a “canvas” to paint on. In your hierarchy, right-click and got to 2D Object -> Tilemap.

Unity 2D Object menu with Tilemap selected

What it has done is created a grid, and inside that grid is our “canvas”, also known as a tilemap. In order to start painting you need to familiarize your self with the toolbar in the Tile Palette tab. With your rule tile selected, start experimenting with the various types of brushes. Once you feel pretty confident with the tools, start creating your level!

Adding the character

The last thing we have to do to our tilemap is to make it have physics interactions. Right now anything we put on it would just fall through the world. To fix this, Unity Technologies released a new collider component called the Tilemap Collider. This behaves just like you would expect it to based on the title, it creates a collider around each tile. Go to your Tilemap and click Add Component.

Tilemap object with Tilemap Collider 2D Component selected

Search “Tile” and it should appear first. Once you add this, you can drag the character into the scene!

Robot character dragged from assets onto game screen

We will be using the default character that came with the 2D standard asset pack. You can find the character by either going to Standard Assets -> 2D -> Prefabs and then dragging in the “CharacterRobotBoy”, or, you can just search “CharacterRobotBoy” and access it from there. Once the character is in the scene, you can hit play and move the character through the arrow keys. You may have to reposition the camera in order to see the robot. Great! On to the next paragraph!

Creating the enemy

In the “Enemies” folder from the asset pack, pick a certain enemy that you think would go well with your scene.

Various sprite choices to use for the enemy

Drag it into your scene and place it in a sensible spot.

Unity scene view with robot character and grey sun-shaped enemy

Then create a new tag called “Enemy” and assign it to your enemy.

Tags & Layers menu in the Unity Inspector

Saw enemy object with the Enemy Tag highlighted

Now we are going to animate this enemy. You should already have the Animation tab open in the lower window of your workspace. If not, go to Window -> Animation.

Unity Window menu with Animation highlighted

With your enemy selected, click “Create” in the Animation tab.

Unity Timeline with Create button highlighted

Name it “Enemy1Controller”.

File screen with Enemy1Controller animation ready to be saved

Save the animator controller in the Animations folder we created earlier. Next, click “Create” again

Animation screen for saw with Create button

and give the animation a sensible title.

File screen with sawIdle animation about to be saved

Hit the record button and change the Sprite field to the other image that was provided (in my case it was called Saw_move, it may be similar if you chose a different enemy).

Select Sprite window with saw_move sprite selected

Then move about four frames ahead and change the image back to what it was before.

Select sprite window with saw sprite selected

Then move a couple frames forward and change it back to the first image.

Select sprite screen with saw_move sprite selected

Now if you hit play you will see that our enemy is animating! Cool!

Scripting our enemy

Let’s make it so that whenever the character touches the enemy the level restarts. The best way to do this is to actually create a new script and box collider on our robot character.

Robot player character with Box Collider 2D Component attached

Set the box collider to Trigger and make sure it liberally covers the character. Name the new script “EnemyReaction”.

Component search screen with EnemyREaction typed in

Let’s create a new folder called “Scripts” to house this component.

EnemyReaction script with red arrow pointing to Scripts folder

Here is the content of the EnemyReaction script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // This is very important if we want to restart the level

public class EnemyReaction : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
	// This function is called every time another collider overlaps the trigger collider
	void OnTriggerEnter2D (Collider2D other){
		// Checking if the overlapped collider is an enemy
		if (other.CompareTag ("Enemy")) {
			// This scene HAS TO BE IN THE BUILD SETTINGS!!!
			SceneManager.LoadScene ("scene1");
		}
	}
}

In order for this script to work, we need to do a couple of things. First, we need to have a collider on our enemy.

Saw object both in the scene view and Unity Inspector

A simple box collider works best for covering all needs. Then, we need to save this scene as “scene1”.

scene1 Unity scene circled next to the Tiles folder

Just save it in the root folder since we only have one, but if you are planning on having multiple scenes then you should create a new folder. Finally, that scene has to be put in the build settings. To do this, just go to File -> Build Settings

Unity File menu with Build Settings selected

and then click “Add Open Scenes”.

Unity Build Settings menu with Add Open Scenes highlighted

Now everything should work! Hit play and run into the enemy, the level restarts!

Cinemachine and Timeline

We now come to the last part of this tutorial. In this part, we will be using Cinemachine and the Timeline editor. Let’s start with Cinemachine. You’ll notice that our camera isn’t following the character when he moves around. We can fix this by creating what is known as a Virtual Camera. Navigate to your toolbar and go to Cinemachine -> Create 2D Camera.

Cinemachine menu with Create 2D Camera highlighted

Then assign the “follow” field on this camera to be the CharacterRobotBoy. Rename this to “PlayerCam”. Set the Aim to “Do Nothing” and set the Body to “Framing Transposer”.

PlayerCam object with Follow parameter set to Robot player character

Now, in the game view, you will notice a set of blue and red areas.

Robot player character surrounded by blue and red rectangles

You can click and drag these areas to change their shape. The one that is harder to see is the clear zone. It sits right on top of our character. This is known as the Dead Zone. The Camera will not do anything as long as the character is in this zone. The blue zone is the Soft Zone. If the character crosses over into this zone the camera will reposition itself so that the character is back in the Dead Zone. The red zone is known as the Bias. The character will never ever cross into this area. Now that you have this knowledge, change the size of these areas in order to get the right following style that you like. Next, let’s have a look at the Timeline Editor. Create a new, empty game object, named “Timeline”…

Timeline object selected in Hierarchy with red line pointing to Create on Animation menu

…and then click Create in the Timeline Editor. Call it “TheTimeline” and save it in the root folder.

File screen with TheTimeline animation ready to be saved

You can have multiple timeline editors in a scene, which just adds to the complexity so we just have one. With this Timeline, we will create a cutscene where the camera views the entire level and then zooms in on the player. This will occur as soon as the scene starts. In order to do this, we need to combine Cinemachine and the Timeline Editor. We can do this through Cinemachine shot clips. In the Timeline, click “Add” and then go to Cinemachine.Timeline -> Cinemachine Track.

Timeline window with Cinemachine Timeline, Cinemachine Track selected

Drag the Main Camera into the field.

Main Camera with red line showing it in Unity Timeline

Then right-click and go to “Add Cinemachine Shot Clip”.

Timeline view with menu open showing Add Cinemachine Shot Clip selected

With this track, we can specify how long we want a certain camera to be active. Let’s create a new 2D camera and position it so that we can see the entire level. Name this one “FullLevel”.

FullLevel object with Transform and Cinemachine Components circled

This will be our first camera so select the Cinemachine shot clip and drag this camera into the “Virtual Camera” field.

FullLevel object set as the Cinemachine camera in Inspector

Set how long you want this camera to last. One thing that helps is to set the timescale to be in second and not frames.

Unity Timeline menu with Seconds option selected

Next, we need to create another clip for the player camera.

Game overview with Timeline and Inspector open

Place this at the end of the other clip. Drag either one of the clips on top of each other in order to smoothly transition. Now if you hit play, we have a pretty neat cutscene! But notice when the last track ends it goes back to the first camera instead of staying on the player. The easiest way to fix this is by deactivating the first camera after we have transitioned into the second. We can do this by using an Activation Track. As its title implies, the specified game object will stay active as long as the track persists. Create an Activation track…

Timeline menu with Activation Track selected

…and drag the first camera into its field.

FullLevel object with red line showing it in Unity Timeline

Then set the length to be a little after the transition. Now if you hit play, it all looks good and the player camera persists!

Outro

Congratulations on getting to the end of this tutorial. As I said before, this is not meant to be exhaustive. In order to find out more about these tools, you can either read the tutorials linked above, or you can explore them on your own! In either case:

Keep making great games!


Viewing all articles
Browse latest Browse all 1620

Trending Articles