How To Make a 2.5D Game With Unity Tutorial: Part 1

Marin Todorov
Learn how to create a simple 2.5D game with Unity!

Learn how to create a simple 2.5D game with Unity!

A while back, you guys said you wanted a tutorial on “How To Make a 2.5D” game.” You guys wanted it, you got it!

If you don’t know what a 2.5D game is, it’s basically a 3D game that you squish so the gameplay is only along a 2D axis.

Some good examples are Super Mario Brothers Wii, Little Big Planet, or Paper Monsters.

One great way to make 2.5D games (or 3D games too!) is via a popular, easy, and affordable game development tool named Unity.

So in this tutorial series, I’m going to show you how you can use Unity to create a simple 2.5D game called “Shark Bomber!”

If you’re new to Unity but would like to learn it, this tutorial is for you! You’ll learn how to make a simple game from scratch and learn a ton along the way.

In this game, you take control of a small but (well armed) airplane, and your job is to bomb the evil sharks while protecting the lovely clownfishes!

Unity doesn’t use Objective-C, so for this tutorial, you don’t need any Objective-C experience. However, some experience with an OO language is a plus – ideally C#, Java, or Actionscript.

Keep in mind that this is a Mac-users tutorial – Windows users might not find it accurate for their setups. Also, keep in mind you will test on an iOS device only (not the simulator) – so make sure you have a device ready to work with!

OK, so let’s dive into Unity – but be sure to avoid those sharks! :]

Installing Unity

First let’s install the Unity editor – if you already have it on your mac just skip this step.

Download Unity from its download page. Once you have the DMG file, mount it and start the Unity installer, after a standard installation procedure you will have a /Applications/Unity folder where the binaries are located.

Start Unity, and click the “Register” button (don’t worry, you can try it out for free). Select “Internet activation”, click Next, and fill in the form on the web page that appears.

Important: For this tutorial, you need to choose the “Start Pro / iOS Trial” option so you can publish to the iPhone (not the plain “Free” option!)

After registration completes, Unity should start up and you should see a window that looks something like this:

Welcome to Unity!

Close down the “Welcome to Unity” popup, go to File\New Project, choose a folder somewhere on your disk and name the project SharkBomber. Make sure all the packages are unselected, and click Create Project.

Now you’re at a blank slate. Wow there are a lot of buttons, eh? Don’t worry – in the next section we’ll go over it bit by bit.

Unity Editor Overview

Let’s do some additional setup to get things into a known configuration.

In the top right-hand corner of the application window you’ll find a select box – select “Tall” from the list. This will rearrange the window contents (the default was “Wide” FYI).

Now find the tab in the top left corner (just below the tool bar) saying “Game”- drag it near the bottom of the window until you see indication it’ll snap to the bottom and drop it there.

Dragging the game tab to the bottom of the Unity editor

Now you should see the layout from the picture below:

Unity Editor Layout

Let’s go quickly over the different panels:

  1. Scene: Here you move your 3D models around and can browse your 3D world.
  2. Game: This is what your selected camera (in this case the main camera) sees – real-time until you use the editor as well; in this strip your game runs when you hit “Run” and you can test your game.
  3. Hierarchy: Your objects’ tree (much like the HTML DOM for example), currently you have only a camera, but we’ll add some stuff here later on; the objects in this list are currently present on the scene.
  4. Project: This is the contents of your project, your assets, audio files, everything you will be using now or later on.
  5. Inspector: Here you see all the properties of the selected object in the scene and you can adjust them; unique about Unity is that the Inspector is alive when you run your scene so it’s your debugger too!
  6. Toolbar: Here you have the tools to interact with the objects in your scene and the Run and Pause buttons to test your scene.

In your Unity3D project you can have many different scenes and you can switch between them. Currently you have one empty scene open in the editor. Let’s save it.

  1. Right-click inside the Project panel and choose “Create/Folder” – a new folder appears.
  2. Rename it to “Scenes” – you can do this by single left click on the folder name, or by selecting the folder and pressing “Enter”.
  3. Now from the main menu choose “File/Save scene” – navigate the save dialogue to [your project directory]/Assets/Scenes and save the scene as “LevelScene”.

Phew! OK – that’s done. Let’s check – in your Project panel open the Scenes folder – there’s your LevelScene scene. Cool!

Now we are ready to run the game – hit the Play button on top! Not much changes – but in fact your game is running inside the Game panel! Don’t forget to stop the game by clicking the Play button again (this is important!)

Setting up an iPhone Unity3D project

One of the nice things about Unity is that it can build games for iPhone, Mac, Wii and other platforms. In this tutorial we’ll be building an iPhone game so we need to setup some details first.

From the menu, choose “File/Build Settings” and click the “Add current” button to add the currently selected scene to the project. You can see when it’s added that it’s got an index of “0”, which means it’ll be the first scene to be loaded when the game starts. This is exactly what we want.

From the Platform list select iOS and click “Switch platform” button. The unity logo appears now in the iOS row.

This is all the setup we need for now, click “Player settings” and close this popup window. You’ll notice the Player settings opened in the Inspector, we need to set couple of things in here too.

In the “Per platform” strip make sure the tab showing an iPhone is selected, like so:

Unity iOS Platform Settings

There’s lot of settings here, you know most of them from Xcode, so you can play and explore yourself later on.

Now use this inspector to make the following changes:

  1. In the “Resolution and Presentation” strip for “Default orientation” select “Landscape Left”.
  2. In the “Other settings” strip for Bundle Identifier put in whatever you want (except the default value)
  3. In the “Other settings” strip set the Target device to “iPhone only”.

One final touch: To the left under the “Game” tab now you have available different orientations/resolutions – select “iPhone Wide(480×320)” to match the default landscape orientation.

Configuring Unity for iOS

Congrats – you now have a basic “Hello World” project that you can try out on your iPhone!

Running the Game on Your iPhone

Unity to Xcode - Awww, yeah!

Unity to Xcode - Awww, yeah!

To test everything we did up to now, we’re going to finish by testing the project in Xcode and your iPhone.

Startup your favorite Xcode version – close the welcome screen if there’s one and switch back to Unity. This is a trick how to tell Unity which Xcode version to use – just have it running aside.

Back in Unity, from the menu choose “File\Build&Run”- this will popup again the Build Settings, click “Build and Run” button.

You will be asked where do you want to save your Xcode project (they don’t really say that, but this is what they are asking). Inside your project directory create a folder called “SharkBomberXcode” (this is where your Xcode stuff will reside) and as file name put in “SharkBomber”.

After few moments the project is built and you will have Xcode window popup with a project opened called Unity-iPhone. What happened is that Unity has generated the source code of an Xcode project and you have now this generated project ready to build&run from Xcode.

You might wanna have a look at the source code – but it’s actually a boilerplate which loads the mono framework included as few chunky dll files and some assets, so there’s not much you can play with.

You have 2 targets, so make sure your iOS device is plugged in and select the “Unity-iPhone” target and your device. (I can’t make the Simulator target run, if you do great, but for now I’ll stick to the device).

Moment of truth – hit the Run button, and your Unity project now runs on your iPhone!

Running a Unity game on your iPhone

Good job, you can see the default Unity start screen and then just the blue background of your scene (and the words “trial version” in a corner).

Stop the Run task, switch back to Unity, and save your project.

Setting up the Scene

First let’s setup the main camera on the scene. Select “Main Camera” in “Hierarchy”, in the Inspector find “Projection” and set it to “Orthographic”, “Size” set to “10”, in Clipping Planes set “Near” to “0.5” and Far to “22”. Now you see a box nearby your camera inside the scene- this is the bounds of what will be seen on the screen from your world.

Notice we’ve set the camera projection to “Orthographic”- this means the depth coordinate won’t affect how things look on the screen – we’ll be effectively creating a 2D game. For the moment let’s work like that until you get used to Unity, then we’ll switch to 3D projection.

Set your camera position (in the Inspector) X, Y and Z to [0,0,0]. Note from now on when I write position to [x,y,z], just set the 3 values in the 3 boxes for that property.

Right-click in the Project panel and again choose “Create/Folder”, call the new folder “Textures”. Then download this background image I’ve put together for the game and save it somewhere on your disc. Drag the background image from Finder and drop it onto the “Textures” folder you just created.

It takes good 20 seconds on my iMac to finish the import, but when it’s done do open the folder, select the “background” texture, and in the inspector look at the texture’s properties. At the very bottom in the preview panel it says “RGB Compressed PVRTC 4bits.” Hmmm, so Unity figured out we’re importing a texture and compressed it on the go – sweet!

Importing a Texture in Unity

From the menu choose “GameObject\Create other\Plane” and you will see a blue rectangle next to the camera. This is the plane we just added to the scene; we’re going to apply the texture we’ve got to it.

Select “Plane” in the Hieararchy panel, in the Inspector in the text field at the top where it says “Plane” enter “Background”. This changes the object’s name, this is how you rename an object. Drag the “background” texture from the Project panel and drop it onto the “Background” object in Hierarchy. Set the position of the plane in the Inspector to [4, 0, 20], the Rotation to [90, 180, 0] and Scale to [10, 1, 5] – this as you see in the “Scene” panel scales and rotates the plane so that it faces the camera – this way the camera will see the plane as the game’s background.

Now in order to see clearly what we have on the scene we’ll need some light (much as in real life) – choose “GameObject\Create other\Directional Light” – this will put some light on your scene. Select Directional Light in “Hierarchy” and set the following Position coordinates [0, 0, 0].

Adding a directional light in Unity

Now we have all the setup and the background of the scene, it’s time to add some objects and make them move around!

Adding 3D Objects to the Scene

From the menu choose “GameObject\Create other\Cube” – this adds a cube object to your scene. This will be the game player, so rename it to “Player”.

Set the following position: [-15, 5.3, 8]. You’ll see the cube appearing near the left side of the screen in the “Game” panel – this is where our plane will start and will move over the sea surface to the other end of the screen.

Now let’s import the plane model! We’ll be using free 3D models produced by Reiner “Tiles” Prokein and released for free on his website (also have a look at his license for the models).

To start, download his airplane model and unarchive the contents.

Right-click inside the “Project” panel and choose “Create/Folder”, rename the folder to “Models”. From the the folder where you unarchived the plane model drag the file “airplane_linnen_mesh.obj” and drop it onto the “Models” folder in the “Project” panel.

Then right-click the “Models” folder and choose “Create/Folder”, rename the new subfolder to “Textures” – here we’ll save the textures applied to models. Drag the file “airplane_linnen_tex.bmp” and drop it onto the newly created “Textures” folder.

Next, select the “Player” object in the “Hierarchy” panel, look in the “Inspector” – the “Mesh Filter” strip is the filter which sets your object’s geometry (right now it sets a cube geometry); on the row saying “Mesh – Cube” find the little circle with a dot in the middle and click it – this opens a popup where you should double click the plane model and this will change your object’s geometry to an airplane.

Setting player to a model with Unity

Now one fine detail – the airplane looks a bit messed up. I’m no 3D expert, but I found what fixes this in Unity: select “airplane_linen_mesh” in “Project” panel then in the “Inspector” find “Normals” and select “Calculate”, then scroll down and click “Apply” button.

Cool – now you see the smooth airplane in the scene! Let’s apply also its texture: Drag “airplane_linnen_tex” texture from your “Project” panel and drop it onto “Player” in the “Hierarchy” panel. Unity automatically applies the texture to the airplane model we have on the scene.

Final touches for the airplane: to the “Player” object set Rotation to [0, 90, 350] and Scale to [0.7, 0.7, 0.7], this will rotate and scale the plane so it looks like flying just over the sea surface.

This game might not be Call of Duty quite yet, but stay tuned, because in the next section we’re going to make our airplane fly! :D

Beginning Unity3D programming with C#

As you’ve already seen in the Build Settings dialogue Unity can build your project to a Wii game, an iPhone game, standalone Mac game, and so forth. Because Unity is so omnipotent it needs some kind of intermediate layer where you can program your game once; and each different build translates it to platform specific code.

So oddly enough, to program in Unity you will be using C# (not Objective-C!), and when Unity generates your Xcode project it will translate that C# code to platform specific code automatically!

Right-click inside the “Project” panel and choose “Create/Folder”, rename the new folder to “Class”. Right-click the “Class” folder and choose “Create/C Sharp Script”, rename the new file to “PlayerClass”. Right-click inside the “Project” panel and choose “Sync MonoDevelop Project”- this opens the MonoDevelop IDE – this is the IDE where you can program in C#.

Note: MonoDevelop is a program ported from Linux, as you can see by the user interface skin called Gnome, so it’s normal if it crashes every now and then, especially when you try to resize the window. If that happens, just start it again by clicking “Sync MonoDevelop Project”.

MonoDevelop editor launched from Unity

Here are the three major areas in the MonoDevelop GUI:

  1. Your MonoDevelop project browser – in Assets/Class you will find your PlayerClass.cs file.
  2. The currently open class outline
  3. Editor area – there’s some syntax highlighting and some auto-complete which will help you coding.

Find your PlayerClass.cs file in the project browser and double click it to open it in the editor. Make sure that the class looks like the following:

using UnityEngine;
using System.Collections;
 
public class PlayerClass : MonoBehaviour {
 
	// Use this for initialization
	void Start () {
 
	}
 
	// Update is called once per frame
	void Update () {
 
	}
}

The clause “using” includes the given libraries and frameworks, UnityEngine is the library which gives you access to things like iPhone’s accelerometer, keyboard input and other handy stuff.

You define your new class and inherit from MonoBehaviour – this gives you lots of stuff for free: you can override a long list of methods which are called when given events are triggered.

Just few lines below you have empty Start and Update methods – these are 2 important events.

  • Start is called when your object appears on the scene so you can make your initialization (much like viewDidAppear: in UIController).
  • Update is called when every frame is rendered (i.e. could be 30, 60 or 100 times a second, you never know how often) and here’s where you do your movements, game logic, etc.

Now let’s switch back to Unity for a moment. We’ll want to make the airplane fly over the sea and when it goes out of the right side of the screen to appear again from the left side. Let’s measure at what position we need to move the airplane to the left. In the “Scene” panel at the top right corner you see the orientation gizmo – click on the X handle (it’s a kind of red cone, I’ll call it handle):

Unity navigation gizmo

This will rotate the scene and orient it horizontally towards you. Click again the handle which is now on the left side of the gizmo – this will rotate the scene around, you might need to click the left handle few times until you see the scene frontal like this:

Rotating a Unity scene with the navigation gizmo

Now you can use the mouse scroll wheel to zoom in/zoom out on the scene and fit it inside the “Scene” panel. Make sure the move tool is selected in the toolbar above and select the “Player” in the “Hierarchy”.

Unity move tool selected

Now you see that a new gizmo appeared attached to the airplane with a green and red arrows. Now, you can drag the arrows and they will move the airplane in the axis the arrows represent:

Moving the player in Unity horizontally with the move gizmo

What you need to do is grab the red arrow (horizontal axis) and drag the airplane to the right until it goes out of the “Game” panel below.

So start dragging inside the “Scene” panel, but while looking at the “Game” panel. Leave the airplane just outside the visible screen and have a look at its position in the “Inspector”.

X should be now around “17.25” – so this is the right bound of the screen, you can drag the plane left and you’ll see the left bound is about “-17.25″, so we’ll use “18” and “-18″ to wrap the airplane flight. Bring back the airplane to just about the left side of the screen where it was before.

Switch back to MonoDevelop, and make the following changes to PlayerClass.cs:

//just after class declaration line
public float speed;
 
//inside the Update method
if (transform.position.x > 18) {
	//get new speed
	speed = Random.Range(8f,12f);
	transform.position = new Vector3( -18f, transform.position.y, transform.position.z );
}		
transform.Translate(0, 0, speed * Time.deltaTime);

As you already guessed, you just declared a public property on your class called “speed”, but what is unique to Unity is that all public class properties are also accessible via… the “Inspector” panel (ta-daaaah)!

So you can set the values of your class properties from the IDE and you can monitor the values of your properties while the game runs in real timefor free – how cool is that?!

The “transform” variable is a property on every game object (and everything inside a scene is a game object) which handles the object’s position in space: rotation, position, scale, etc. So on every Update call to translate the object’s position so that it moves to the right of the screen.

We can’t just move the plane a set amount per call to Update, because nobody knows how many times this will actually be called per second. Instead, we define the speed to be units per second, and divide the speed by the amount of time elapsed since the last call to Update (Time.deltaTime). This way the object moves always with the same speed independently from the current frame rate.

The call to Translate takes 3 values – the translation it has to do on each axis. You probably notice that we are moving the airplane on the Z axis (3rd parameter) – we have to do that because we rotated the plane on the scene, so translating the Z axis moves it to the right from the perspective of the player!

Look at the “if” statement – we check if transform.position.x is bigger than 18 (remember why?) and if so, we set the airplane’s position to same coordinates but “-18″ on the X axis. We use new Vector3(x,y,z) to set the position – we’ll be using a lot of these vectors for all positioning; you notice also we set a random speed between 8 and 12 – this is just to make the plane move more randomly to keep things interesting.

At this point we are ready to see the airplane move!

Switch back to Unity. Drag the “PlayerClass” from “Project” panel onto “Player” in the “Hierarchy” panel – this way you attach the class to a game object. Select “Player” in “Hierarchy” and look in the “Inspector”- you’ll see a new strip appeared called “Player Class (Script)” where you also see your public property! yay! Set a value of “12” for it.

OK. Ready? Hit that Play button! Woot! You can see in both “Scene” and “Game” panels that the airplane flies around and when goes out of the right comes back from the left side. Also notice in the “Inspector” the X value of position is alive as well – it shows you where the plane is at any given moment. Also Speed changes to random values every time the plane flight wraps.

Dynamic Properties in Unity

Once you’re done enjoying this coolness, don’t forget to hit Play again to stop the game.

Next up, time to give this plane a formidable foe – a menacing shark! Now that you’re familiar with the basics, things will go faster since we won’t be doing anything new for a while.

Need a break? We’ve covered a lot here! So if you get tired or just need to have a break, no problem – just save your Unity project and you can open it later. But! When you open a Unity project it opens by default an empty scene. To load the scene you are working on – double click “LevelScene” in the “Project” panel – now you can continue working.

Jumping the Shark

Go ahead and download and unarchive the Shark model. As you did before with the airplane, drag the file “shark.obj” onto the “Project” panel inside the “Models” folder and “sharktexture.bmp” inside “Models/Textures”.

From the menu choose “GameObject/Create other/Capsule” – rename the “Capsule” object in “Hierarchy” to “Shark”. In “Inspector” inside the “Mesh Filter” strip click the circle with dot inside and in the popup window double click the Shark model. Now you should see the Shark geometry in the “Scene” and “Game” panels.

Drag “sharktexture” from “Project” panel (it’s inside Models/Textures) onto the “Shark” object in “Hierarchy” – this gives your shark a vigorous mouth and some evil eyes! Pfew – I already want to bomb it!

Make sure “Shark” is selected and set the following properties in the “Inspector”: Position – [20, -3, 8], Scale – [1.2, 1.2, 1.2] – this will put the shark just right off the camera visible box – it’ll start moving from there towards the left side of the screen.

Adding a shark to the game

Now since we’d want the shark to interact with our bombs (by exploding, mwhahahahah!) we want the Collider of the shark to match more or less the shark’s geometry. As you see there’s a green capsule attached to the shark inside the scene. This is the shark’s collider. Let’s have it matching this evil predator’s body.

In the “Inspector” find the “Capsule Collider” strip and set the following values: Radius to “1”, Height to “5”, Direction “X-Axis”, Center to [0, 0, 0]. Now you see the capsule collider has rotated and matches more or less the shark’s body – better!

Modifying the capture collider settings so the collision shape matches the sharks shape

Last – select “shark” model in “Project” panel “Models” folder then in the “Inspector” find “Normals” and select “Calculate”, then scroll down and click “Apply” button.

Right-click inside the “Project” panel in “Class” folder and choose “Create/C Sharp Script”, rename the new script to FishClass. Righ-click and choose “Sync MonoDevelop Project”.

MonoDevelop will pop up. Open the FishClass.cs file and put inside the following code:

using UnityEngine;
using System.Collections;
 
public class FishClass : MonoBehaviour {
 
	public float speed = 6f;
 
	// Update is called once per frame
	void Update () {
		if (transform.position.x < -30 || transform.position.x > 30) {
			//turn around
			transform.Rotate(new Vector3(0,180,0));
			transform.Translate( new Vector3(-10, -transform.position.y + Random.Range(-4,-1),0) );
 
			//get new speed
			speed = Random.Range(6f,10f);
		}
		transform.Translate( new Vector3(-speed*Time.deltaTime,0,0) );
	}	
}

It’s pretty similar to what we have already for the airplane. We have a speed property (per second) and in the Update event handler we use transform.Translate to move the shark.

Notice this time I used:

transform.Translate( new Vector3(x,y,z) );

This is just to demo that some of these methods can take different parameters – however passing separately 3 values or 1 vector is pretty much the same.

Now let’s see what the shark does when it reaches the bounds of the screen (-30 and 30 in this case, so there’s is a moment when the shark is offscreen, so you can’t easily ambush it when entering back).

When the shark reaches left or right bound it turns around moves a bit towards the bound and changes speed. This way it just goes back and forth, back and forth continuously.

The call to transform.Rotate(new Vector3(x,y,z)) obviously rotates the object around the axis by the given values, and transform.Translate(new Vector3(x,y,z)) you already know well.

Pretty easy! Switch back to Unity and drag the “FishClass” script onto the “Shark” object in “Hierarchy”. Now hit Play: you can see the huge shark going back and forth waiting to be bombed. Good job!

Adding shark into scene

Adding the Clown Fish

Let’s do the same procedure again for our ClownFish. I’ll put it into a nice list for quick reference:

  1. Download and unarchive the ClownFish model.
  2. Drag “mesh_clownfish.obj” into “Project” panel inside “Models” folder and “clownfish.bmp” inside “Models/Textures”.
  3. Choose “GameObject/Create other/Capsule” and rename the “Capsule” object in “Hierarchy” to “ClownFish”.
  4. Click “Mesh Filter” circle-with-a-dot-button and from the popup double click the clownfish geometry.
  5. Drag the “clownfish” model texture onto “ClownFish” object in “Hierarchy”.
  6. While having “ClownFish” selected change the following properties in the “Inspector”:
    • Position to [-20, -1, 7]
    • Rotation to [0, 180, 0]
    • Scale to [0.4, 0.3, 0.3]
  7. With the “ClownFish” still selected, change the following properties in the Capsule Collider strip:
    • Radius to “4”
    • Height to “4”
    • Direction to “Z-axis”
    • Center to [0, 0, 0].
  8. Drag “FishClass” from “Project” panel onto the “ClownFish” object in “Hierarchy”. This will assign the same generic fish class also to the clownfish.
  9. Select “mesh_clownfish” model in “Project” panel “Models” folder then in the “Inspector” find “Normals” and select “Calculate”, then scroll down and click “Apply” button.

Hit Play and see what happens – now you have two moving fish without having to write any extra code!

Scrolling fish with Unity

Everything works perfect – the fish go back and forth, plane is wrapping. We need some boooombs!

Set Us Up The Bomb

Download and unarchive the Can model. As usual, drag the “colourcan.obj” file in “Project” panel “Models” folder and “cantex.bmp” file in “Models/Textures”.

From the menu “GameObject/Create Other/Capsule”, rename the object to “Bomb”. From the Mesh Filter popup double click the can geometry. Drag the “cantex” texture onto the “Bomb” object in “Hierarchy”. In “Inspector” “Capsule collider” click this button to open the popup menu:

Capsule Collider popup menu

When the popup menu appears, choose “Reset” – this way the collider automatically will take the size of the geometry assigned – cool!

Next select the “colourcan” model in “Project” panel “Models” folder then in the “Inspector” find “Normals” and select “Calculate”, then scroll down and click “Apply” button.

Now let’s dive into new stuff! Select the bomb object again, and inside the Capsule Collider strip check the “Is Trigger” checkbox – aha! Check this to make the bomb object will trigger event when it collides with other objects.

But for this to happen we need to also assign a Rigid Body to the bomb (as at least one of the colliding objects needs to have a rigid body). From the menu choose “Component/Physics/Rigidbody” (Bomb should be selected in the Hierarchy!).

Once you do this, a new strip should appear in the “Inspector” called “Rigidbody”. Uncheck “Use gravity” (we won’t use gravity) and check “Is Kinematic” to be able to control the body programatically. This was all we needed to have collisions enabled!

Adding a rigid body for collisions in Unity

Download and save on your disc this bomb releasing sound (which I made myself, lol!)

We would like to play this sound when the airplane releases a bomb, i.e. when the bomb first appears on the screen. Let’s do that!

Right-click in the “Project” panel and choose “Create/Folder”, rename the new folder to “Audio”. Drag the “bahh1.aif” file onto the “Audio” folder. Next drag the “bahh1″ sound file from “Project” panel onto the “Bomb” object in “Hierarchy”.

Believe it or not, that’s all we need to do – the sound is attached to the bomb and will play when the bomb appears on screen. Notice how easy some things are with Unity?

Select the “Bomb” object in “Hierarchy” and in “Inspector” find the “Audio Source” strip: see that “Play On Awake” checkbox is checked – this tells the audio to play when the object appears on the scene. Also look at the “Scene” panel – see the bomb has now a speaker attached?

Setting the audio source for an object in Unity

Prefabricating your Game Objects

Remember that “Hierarchy” shows what’s on the scene currently, and “Project” holds all your object for you? This has to do something with our goal here – have many bombs loaded on the plane and release them at will into the sea.

What we are going to do is – we are going to prefabricate a game object (it will be ready and set to appear on the scene), but we won’t add it to the scene- we are going to instantiate (or clone if you are a sci-fi fan) this “prefab” into a real living game object on the scene.

Right-click inside the “Project” panel and choose “Create/Folder”, rename it to “Prefabs”. Right-click “Prefabs” and choose “Create/Prefab”. Rename the new prefab to “BombPrefab”. Notice the little cube icon is white – this indicates an empty prefab.

Now – drag the “Bomb” from Hierarchy onto the “BombPrefab” in “Project”. Notice the cube icon is now blue – means a full prefab, ready to be cloned. Also important – look at the “Hierarchy” panel now – “Bomb” font changed to blue color – that means this object now is an instance of a prefab.

Now that we have our bomb cookie cutter set, we don’t need the original bomb object on the scene – right-click on “Bomb” in “Hierarchy” and choose “Delete”.

Let’s get coding! Switch to MonoDevelop and open up the PlayerClass.cs. under the “speed” property declaration add:

public GameObject bombPrefab;

Have you guessed already? In this property we’ll hold a reference to the BombPrefab and we’ll make instances as we wish. Notice the property type is “GameObject”, as I said earlier everything in the game is a GameObject (much like NSObject in Cocoa), so it’s safe to set that type for just about anything.

Now switch back to Unity and select the “Player”. As you expected in the “Inspector” under “Script” there’s a new property “BombPrefab”. Let’s set its value: drag the “BombPrefab” from “Project” panel onto the “Inspector” where it says “None(GameObject)” and drop – now the field indicates it has BombPrefab prefab attached as value. Cool!

We’re going to need a C# class also for the bomb – right-click inside “Project” in “Class” folder and choose “Create/C Sharp Script”, rename it to “BombClass”. Right-click and “Sync MonoDevelop Project” – MonoDevelop pops up. Open up BombClass.cs and replace the contents with this code:

using UnityEngine;
using System.Collections;
 
public class BombClass : MonoBehaviour {
	private float ySpeed = -4f;
 
	// Update is called once per frame
	void Update () {
		transform.Translate( new Vector3(0f, ySpeed*Time.deltaTime, 0f) );
		if (transform.position.y < -11) {
			Destroy(this.gameObject);
		}
	}
}

This is pretty similar to everything we’ve done up to now – we translate the object every frame and when out of the screen bounds we react appropriately. In the bomb case we just want to destroy the object since we can always make new ones from our bomb prefab.

In the code note that “this” refers to the C# bomb class, while the gameObject property refers to the object on the scene – so we destroy the object on the scene and all components attached to it. We’ll have a look at the game object hierarchy in Part 2 when you access components attached to an object programatically.

Bombing that shark!

Finally the part you’ve been waiting for – gratuitous violence! :]

Open up PlayerClass.cs. At the end of the Update method add:

if (Input.anyKeyDown) {
	GameObject bombObject = (GameObject)Instantiate(bombPrefab);
	bombObject.transform.position = this.gameObject.transform.position;
}

Let’s go over this line by line.

  1. Input is the class giving you access to keyboard, mouse, accelerometer and touches. Input.anyKeyDown is true when a key is pressed, this happens only once – i.e. when the button was first pressed; then Input.anyKeyDown is false again until another key is pressed. anyKeyDown is actually a handy abstraction – it actually is true when a mouse button was clicked, keyboard key was pressed or (!) a tap on the iPhone’s screen was received.
  2. (GameObject)Instantiate(bombPrefab) is the magic line that creates an instance from a prefab and adds it to the scene.
  3. Finally we set the position of the bomb to be same as the airplane’s.

Cool – we have our bomb created when the player taps the screen, it then starts to fall down and when out of the screen destroys itself.

Let’s give it a try! Switch back to Unity and hit Play – now if you click inside the “Game” panel (simulating a tap) you will see a bomb is created where the plane is at that point.

Click many times – many bombs are created. You should also hear the bomb sounds. But the bombs don’t fall down! Why? Can you figure out what’s the problem by yourselves already? Answer after the break.

Cans in Unity game not falling down

I hope you figured it out, but here’s what’s the problem: you haven’t yet assigned the BombClass script to the Bomb Prefab – that’s why the bombs don’t fall down. Drag “BombClass” from your “Project” panel “Class” folder onto “BombPrefab” in “Prefabs” folder in the same panel. Check in the “Inspector” if you see the Bomb Class Script strip. Now hit Play again. That’s better!

Properly falling cans in Unity game

Still not perfect though – those sharks don’t die when you hit them. Since we already configured the colliders and the rigidbody component of the bomb, we just need to add the code to react to collision. Switch back to MonoDevelop and add this new method to the BombClass:

void OnTriggerEnter(Collider obj) {
	if (obj.gameObject.name == "Shark") {
		//reset shark
		obj.gameObject.transform.rotation = Quaternion.identity;
		obj.gameObject.transform.position = new Vector3(20f, -3f, 8f);
		Destroy(this.gameObject);
	}
}

Let’s go over the code line by line again:

  1. OnTriggerEnter is a method called when the body attached collides with another body, and the 2nd body is passed as a parameter.
  2. Here we check if the object the bomb hits is called “Shark”.
  3. If the shark is hit, then 1st reset the object rotation.
  4. 2nd, we reset the shark back to its original position.
  5. Finally, we call destroy this.gameObject to make the bomb disappear from the scene.

Pretty easy again! Isn’t it? That’s about all you need – switch back to Unity, and run your game! Hit sharks disappear and new ones come in.

You can also choose from the menu “File/Build&Run” and when Xcode pops up hit “Run” in Xcode – now you have the game on your iPhone – sweet!

A Simple 2.5D Game Created with Unity!

Where To Go From Here?

Here is a sample project with all of the code from the above tutorial.

I hope you amused yourselves and learned a ton of new things – in Part 2 of the series we’re going to spice up things a notch and make this game really challenging and fun!

In the meantime, if you have any questions about this tutorial or Unity in general, please join the forum discussion below!

Marin Todorov

Marin Todorov is an independent iOS consultant and publisher with complimentary background in server and desktop development.

He started developing on an Apple ][ more than 20 years ago and keeps rocking till today. Meanwhile he has worked in great companies like Monster Technologies and Native Instruments, has lived in 4 different countries, and (more recently) is one the founding memebers of the raywenderlich.com tutorial team.

Besides crafting code, Marin also enjoys bloging, writing books, teaching and training others, and speaking at mobile conferences. He sometimes open sources his code. He walked the way to Santiago.

User Comments

15 Comments

  • Hi,

    Awesome Tutor thank you
    Bobj-c
  • Hey looks like fun! I have been coding nothing but Game Center and NSCoding for at least 2 days now. About ready to scratch my eyes out so I think a nice tutorial break is a good idea tomorrow.

    I would have preferred 2.5D for Cocos2D but you can't please everyone. Someone always has to complain LOL :P

    Thanks.
    Nakor
  • Awesome tutorial!

    Sample project is not complete, right?

    I failed to see the background in the Game view. Do I need to change Render Settings for this game?

    Thanks!
    Ethan
  • Niiiiiiiiiiice, thx a lot ! very good tutorial (=
    But one question : can we insert 3d animated models like a shark with a moving tail when he's swimming for more realistic gameplay.
    Thx again for all your great tutorials.

    P.S : There is a nice application we can found on the AppStore for simulating our games from Unity, it's called : Unity remote, so if you don't have a developing profile for testing the game on your iphone you can use this app, it's very easy to use.
    pol001
  • pol001 wrote:Niiiiiiiiiiice, thx a lot ! very good tutorial (=
    But one question : can we insert 3d animated models like a shark with a moving tail when he's swimming for more realistic gameplay.
    Thx again for all your great tutorials.

    P.S : There is a nice application we can found on the AppStore for simulating our games from Unity, it's called : Unity remote, so if you don't have a developing profile for testing the game on your iphone you can use this app, it's very easy to use.


    Inserting animations within Unity is, from the little knowledge I have of the engine, quite simple. Check out http://www.walkerboystudios.com where they have dozens of hours of free tutorials on Unity, they are very short and easy to pick up :)
    airjordan12345
  • Hi Ray,

    I saw on your wife's blog that you are going to do a tutorial on how to make a catapult game that uses box2d physics similar to angry birds. I'm working on a game with similar functionality and just having a time. I've got lots of programming experience but am totally new to cocos2d and box2d and iphone/ipad development in general. I could really use that tutorial. Do you have any idea when the tutorial will be ready? Any available code at this time? Specifically I'm interested in the parallax scrolling of the background, attaching the catapult to the world and how to move it with the revolute joint. Any help you can give me would be greatly appreciated.

    Thanks,

    Bob Hunt
    Bob Hunt
  • The tutorial is all written, and scheduled for next Thursday and the following Tuesday! Gustavo Ambrozio from the iOS Tutorial Team wrote it and did an amazing job, you guys are gonna love it! :]
    rwenderlich
  • rwenderlich wrote:The tutorial is all written, and scheduled for next Thursday and the following Tuesday! Gustavo Ambrozio from the iOS Tutorial Team wrote it and did an amazing job, you guys are gonna love it! :]


    Thanks Ray, I'm really looking forward to the tutorial. I love your book also. It's really helped me a lot.

    Take care,

    Bob Hunt
    Bob Hunt
  • I'm not sure if I should start a new thread or ask here, but I will give it a try:

    Is it possible to work on the Project in Unity from a Windows PC, then copy the project files over to a Mac and then build it for the iPhone?

    My MBP is quite old and very slow, I just had it crash on me when running Unity so I would rather try it on my workstation. But the deploying to my iPhone went fine. So I hope I can just copy the whole project accross (or place it on a NAS from the beginning).
    falc410
  • Great tutorial. It's great to first meeting with Unity. After this tutorial you'll know what to do with Unity and you can start learn more ;) Thank you, Marin!
    mattmark
  • Thanks for the tutorial; it even works with an older version of Unity (3.5).

    I do have a problem: after the first collision happens (the bomb is destroyed and the shark is reset), subsequent bombs do not collide with the shark. Why is that?
    hyliandanny
  • Thanks for the great tutoria!! I've built a github repo from this tutorial here:

    https://github.com/johnnylambada/unity-shark-bomber

    The nifty thing about the repo is that you can build both Android apks and iPhone ipas using command line tools. It's a nice start to automating the build.

    To do so (assuming a mac with xcode):
    1) git clone https://github.com/johnnylambada/unity-shark-bomber
    2) cd unity-shark-bomber
    3) source scripts/envsetup.sh
    4) hmm # this will give you help
    5) sb-build-android # builds android apk (you may need to tweak the script a bit for your env)
    6) sb-build-ios # builds ipa (you'll need to provide some env vars first. Run the script and it'll tell you what you need)

    enjoy!
    johnnylambada
  • hyliandanny wrote:Thanks for the tutorial; it even works with an older version of Unity (3.5).

    I do have a problem: after the first collision happens (the bomb is destroyed and the shark is reset), subsequent bombs do not collide with the shark. Why is that?


    The tutorial works just fine for me.
    johnnylambada
  • Awasome tutorial ,in a very simple way.thnx!!
    atulawasthi

Other Items of Interest

Ray's Monthly Newsletter

Sign up to receive a monthly newsletter with my favorite dev links, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

Vote for Our Next Tutorial!

Every week, we alternate between Gaming and Non-Gaming tutorial votes. This week: Non-Gaming!

    Loading ... Loading ...

Last week's winner: How to Make a Simple 2D Game with Metal.

Suggest a Tutorial - Past Results

Hang Out With Us!

Every month, we have a free live Tech Talk - come hang out with us!


Coming up in October: Xcode 6 Tips and Tricks!

Sign Up - October

Our Books

Our Team

Tutorial Team

  • Jean-Pierre Distler
  • Matt Galloway

... 53 total!

Update Team

  • Riccardo D'Antoni

... 14 total!

Editorial Team

  • Matt Galloway

... 22 total!

Code Team

  • Orta Therox

... 3 total!

Subject Matter Experts

  • Richard Casey

... 4 total!