Best daily deals

Affiliate links on Android Authority may earn us a commission. Learn more.

How to create a simple 2D platformer for Android in Unity - Part one

A complete tutorial explaining how to create a very basic 2D platform game for Android with touch-screen controls in Unity. By the end of part one you will have a working APK that lets you control a character on a flat surface.
By
May 20, 2016
rushdy game
My wife playing the simple platformer. She immediately worked out how to break it…

If you’re at all interested in developing video games then you should definitely check out Unity. Unity is a 2D and 3D game engine as well as an IDE and builder tool that makes it possible to make professional caliber games with very little in the way of programming knowledge.

Many of the most popular games on the Play Store were made in Unity, including Tomb Raider: GO, Angry Birds and more. So it may come as a surprise just how easy it is to get started with. Often it’s as simple as dragging and dropping various elements around the screen. This guide will show you how to make a 2D platformer and you should be able to create something basic in a couple of hours.

To learn more about why Unity is great, check out my introduction to Unity post. This will also help you to get set up, but to recap: you need to download Unity 5 itself, Visual Studio for your coding and the Android SDK which will come in handy at the end. You also need to sign up for a free account.

Getting started

Once you’ve downloaded and installed Unity and Visual Studio, you’ll be able to launch the software and select ‘New’ to get started.

You’ll then be taken to the next page where you can choose the name for your project and the directory you want to save your files in. You’ll also be able to decide here if you want your project to be 3D or 2D. For the purposes of this particular guide, you’ll select ‘2D’. Now click ‘Create Project’.

unity 1

I’m calling my project ‘Rushdy Worm’ which is the name of a character I used to draw – and also the first full game I ever created!

Adding sprites

Once you’ve loaded up your new project, you’ll be greeted with a blank screen like so:

unity 2

Your windows might be arranged slightly differently but you should always have the same selection to start with. The first thing you’re going to need is the ‘Project’ pane which is down the bottom for me. This is where you can see all the folders containing your various files. Select the ‘Assets’ folder and it will open to the right. Now right click in that folder and select ‘Create > Folder’. You’re going to call this new folder ‘Sprites’. Can you guess what it’s going to contain?

rushdy
ground

For this first version of the game, I’ve created two sprites: ‘ground’ and ‘rushdy’ which represent the floor tile and the main character respectively. You can use mine by right clicking and saving, or you can create your own (I won’t be offended…). Once you’ve created your ‘Sprites’ folder, you can simply drag and drop sprites there from your file explorer. It’s then a matter of dragging them into your ‘Scene’ pane at which point they become part of the game. This is where you can arrange all your individual elements in a level. You can also drag things around the screen or scroll the page by holding ‘alt’ and dragging. Pinch or use your scroll wheel to zoom in and out. Essentially a ‘scene’ is a level, though in future it might also be a menu page or another screen in the game. You can also use the ‘Game’ view in order to see what your camera will see at the starting point in the level.

unity 3

Click ‘Play’ now and you’ll be greeted with your character and your ground tile hovering in space. It’s not terribly fun at this point…

Adding physics

Now comes the part where you’re amazed at just how simple and easy Unity makes everything… First, click on your ground tile in the scene view. This will present you with some information in another window called the ‘Inspector’. This tells you the attributes pertaining to that particular game object (like the size and angle) and lets us tweak them to our heart’s desire.

First, you need to choose ‘Add Component’ and then ‘Physics 2D > Box Collider 2D’. This should create a thin green highlight around your ground tile. This will set where the collision detection will begin and end for that object. If you had a more detailed object then you could select ‘Edge Collider’, which would create a less uniform collider.

unity 4

Now do the same thing for your player sprite. My player sprite is essentially a rectangle, which is going to make life nice and easy for me. I also chose a sprite that faces forward so I can get away without animating him.

At this point, our two objects are now ‘solid’ as far as Unity is concerned but there’s no gravity. To change that, select your main character and choose ‘Add Component’ and then ‘Rigidbody 2D’ which adds 2D physics to your given item. Click play and you’ll see the character drop out of the air and land on the ground. It’s still not that fun but it’s starting to resemble a game…

Adding controls

Most games require some form of input to be fun, so let’s add some controls to our little character. To do this we’re going to try our first bit of code. Don’t worry, it’s pretty easy at this point.

First, create a new folder in Assets and call it ‘Scripts’. Now in this directory, right click and select ‘Create > C# Script’. Call it ‘Controls’ and then double click on it to launch Visual Studio for editing. You will be presented with a screen like this one:

unity 5
Coding in C# isn’t worlds apart from coding in Java for those who are familiar with it. You will still need to end every line with a semi colon and you still use curly brackets for your ‘IF’ statements and likewise for functions.

The basic bit of structure you’re presented with also makes things quite simple. Anything that happens inside Start will deploy as soon as the related object gets created (for our purposes, this will be when the level/game starts). The Update function meanwhile runs continuously and anything you put in here will happen continuously each time the scene refreshes.

If you’re willing to learn some basic C# then you can start doing all manner of fancy things with your game. But otherwise, you can get by just as easily by borrowing code from other people – either by looking online or by using the ‘Asset Store’ that lets you find scripts, assets, sounds and more created by the community. Some of this is free, some of it you will have to pay for. A surprising number of things don’t require any scripting at all either.

In this case, you can use the code I’ve created to add very simple controls to your character:

Code
public class Controls : MonoBehaviour {
    public Rigidbody2D rb;
    public float movespeed;

    void Start () {
        rb = GetComponent<Rigidbody2D>();

    }

    void Update () {

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            rb.velocity = new Vector2(-movespeed, rb.velocity.y);

        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            rb.velocity = new Vector2(movespeed, rb.velocity.y);

        }
    }
}

Here we are creating a floating point variable called movespeed and making it public so that we can access it outside of this script. We’re also creating a reference to the RigidBody2D that we added to our character and calling that rb. You’ll be able to set the value for your public variables using the inspector for the game object to which the script is attached.

In the ‘Start’ function, we tell Unity that rb is the RigidBody2D component attached to our game object. In ‘Update’ we’re listening for the left arrow or right arrow input and then adding velocity to that rigidbody. Basically, we’re telling the physics attached to our player that it now has some momentum heading either left or right.

Now all you need to do is to head back to Unity and drag the ‘Controls’ script onto your player. This is something you’ll need to do a lot – and you’ll find its very easy to forget! Don’t forget to change movespeed to ‘3’ in the inspector either (or whatever speed you like!). Now when you hit play, you’ll be able to control the character left and right with the arrow keys. We’ll be adding touch input later on.

A little polish

Now I’m going to make a few more small changes. First, I’m going to drag my platform from the left corner to the right to make it much wider. I purposefully designed a sprite here that wouldn’t look ‘stretched’ which will make designing levels nice and easy. You can also do this by selecting the resize tool along the top left of the interface, or by changing the scale in the Inspector. Choices.

Next, I’m going to take my camera in the left ‘hierarchy’ pane and drag it to drop it on my player game object (called ‘rushdy’ in my case). This makes the ‘Main Camera’ a ‘child’ of Rushdy (congratulations, it’s a baby camera!). Essentially, this means that the camera will now move when the character moves. I’ve also dropped my camera right into the center of the player by clicking on it in the scene view and then selecting the  move tool in the top left. This now allows us to walk past the right of the screen without losing sight of the character.

unity 6

When you create a real game, you’ll want to give your camera more complex controls to enhance the gameplay. For now though, this will suffice. (If you want to learn more about 2D cameras, check out this article on The Theory and Practice of Cameras in Side-Scrollers.)

Except there’s a small issue we need to change. Right now, if you walk off the edge of the platform the character will spin out of control and the camera will spin with them! This makes for a rather nauseous experience, so click on your player character and then tick ‘Freeze Position Z’ under ‘RigidBody 2D > Constraints’. Now Rushdy will fall without spinning around – like a normal platform character. Rushdy is a weird enough thing to begin with; he doesn’t need any more quirks for the other game characters to tease him about…

I’ve also decided to add a background to my scene so that it looks a little nicer. I’m borrowing a ‘stars’ backdrop I created for another game and I’ve simply added this the same way I added the other sprites. The only difference is that I’ve set the scale (in the Inspector) to 10×10 and I’ve set the ‘order in layer’ to -1. This means that it will be drawn behind the other elements on the screen.

I’ve also set the ‘Z’ position to 20 and changed the Main Camera slightly by setting ‘Projection’ to ‘Perspective’. This means that the background will now appear further away than the foreground and thus move more slowly as we scroll. Thus we have depth.

Adding touch controls

This hardly qualifies as a game at this point, but we now have a little character that can move around the screen, which is more than enough to impress our Mums. The next step then is to install this on our Android devices – but before we can do that we need to add some touch-screen controls.

(For those wondering… yes the current system would work with a Bluetooth keyboard!)

To add these controls, go to GameObject and select ‘UI > Image’. When you do this, you’ll create a new image and at the same time you’ll create a ‘canvas’ which is a floating layer that will appear over your scene and house your UI elements (controls, health, lives etc.). Anything that you want to act as a UI element needs to be a child of your canvas.

Select your new image and use the button in the top left of the inspector to anchor it to the bottom right of the screen. Now copy and paste that image and anchor the new one to the bottom left. I’ve created an arrow sprite too which I dragged and dropped into the ‘Source Image’ box in the inspector. I used the same arrow image for both but set the scale to ‘-1’ for the left one so that it would appear reversed.

right

You also need to make sure these arrows are the right size and in the right position. You can check this by clicking play to see how it looks. We’re also going to add both of these arrows to an additional ‘container’ object by right clicking on the canvas and choosing ‘Create Empty’. Anchor this object to the bottom and click ‘stretch’ to make it as wide as the screen. Now drag your two arrows into here.

I called my container ‘TouchController’ because I lack imagination. Don’t worry if it takes a little fiddling around to get everything right. By the end, it should all look something like this:

unity 8

Next we’re going to add two new public booleans (true or false variables) to our Controls script called moveright and moveleft. Then add this snippet of code to the Update function:

Code
if (moveright)
 {
 rb.velocity = new Vector2(movespeed, rb.velocity.y);
 }
 if (moveleft)
 {
 rb.velocity = new Vector2(-movespeed, rb.velocity.y);
 }

Make sure when you do this that your code isn’t inside any of your ‘if’ statements. Now, every time the scene refreshes our character will move left or right accordingly so long as the relevant boolean is ‘true’. We have to do it this way because we can only detect the buttons going down or being released – we can’t check if they’re currently being held.

Your code should look like this:

unity 13

Next up, we’re creating another new script in our scripts folder and calling it ‘Touch’. Don’t worry, we’re nearly there!

Code
using UnityEngine;
using System.Collections;

public class Touch : MonoBehaviour
        {
            private Controls player;


            void Start()
            {
                player = FindObjectOfType<Controls>();
            }

            public void LeftArrow()
            {
                player.moveright = false;
                player.moveleft = true;
            }
            public void RightArrow()
            {
                player.moveright = true;
                player.moveleft = false;
            }
            public void ReleaseLeftArrow()
            {
                player.moveleft = false;
            }
            public void ReleaseRightArrow()
            {
                player.moveright = false;

            }

        }

Notice that this code is referencing the public booleans attached to our Controls script called moveright and moveleft. We have created functions to set these as true/false and now we just have to map them to our controls.

Drag the ‘Touch’ scrip you just created and drop it on the ‘TouchController’ empty object (which is a child of your canvas and parent of your two arrow images remember). Now select your right button and in the inspector go to ‘Add Component > Event > Event Trigger’. Create two event triggers by selecting ‘Add New Event Type’ and make these ‘Pointer Down’ and ‘Pointer Up’. These represent the images being clicked and released respectively.

Next drag and drop the TouchController container (not the script) into the box that says ‘None (Object)’. You can now choose a function by select ‘Touch’ (your script) from the drop down menu and then choosing the Public Void you created for that purpose. So for your ‘Pointer Down’ event trigger on the right arrow, you want to pick the public void RightArrow and for ‘Pointer Up’ you need to choose ReleaseRightArrow. This will then run the code you added to that function and edit your moveright and moveleft booleans accordingly. Do the same thing for the left arrow.

unity 9

Now if everything works correctly, then you can run the game and you should be able to control the character by either clicking on the on-screen controls or using the keyboard!

Whew! Now all that is left is for us to create an APK…

Creating an APK

To create our APK, we need to first make sure we’ve saved our scene which you can do by clicking on ‘File’ and then ‘Save Scene’. This will automatically save the scene in your Assets folder but for the sake of organization you may want to also create a ‘Scenes’ folder to drop them into.

Now select ‘File > Build Settings’ and make sure to drag the scene you just saved into ‘Scenes In Build’. When you have multiple scenes, the one at the top will be the one that shows first when you load your app (so this will eventually be a menu or a title screen). You’ll also need to select your platform here, which will be ‘PC, Mac and Linux Standalone’ by default. Select ‘Android’ and then click ‘Switch Platform’.

unity 11

Now press ‘Player Settings’ and you’ll see a bunch more options open up in the Inspector. This is where you can create your private key sign and package name (‘bundle identifier’) just as you would do in Android Studio. You’ll also need to show Unity where your Android SDK is located, which you do by going to ‘Edit > Preferences > External Tools’. Make sure when choosing the API Level that you have the correct Android Platform installed.

unity 12

Click ‘Build’ to create your APK and you can try it out on your device!

You can try it for yourself by checking out the project on GitHub. And you can also find the APK there if you don’t want to make it yourself. Then you can have hours of fun moving left and right against a star-filled sky. We could always claim this is an artistic indie game?

It’s not hard though to imagine the few extra elements this would need to become a fun experience. So next time I’ll be discussing how to add multiple levels, lives, collectibles and who-knows what else. Stay tuned!