All posts in "Tutorials"

Building Flappy Bird #2 – Let’s Code

Building Flappy Bird in Unity3D – Part 2 – Let’s code

Code in Unity3D can be done in either C# or Javascript.  If you don’t have a preference, I’d recommend C# for your development.  It’s much more popular in the Unity3D community.  Most samples you find will be in C# only.  For this tutorial though, I’ll provide both the C# & Javascript versions.

Moving the Fish

If you’ve played Flappy Bird before, you know the bird flys to the right of your screen past a bunch of tubes.  Or at least that’s what it looks like.  In reality, the bird is just going up and down and the tubes are moving.  So for our game, all we need the fish to do is go up when we tap the screen (or click the mouse).

First we need to create a folder for our code.  In the root of the Project view, create a new folder named Code.

Project Code

Project Code

In the Code folder, right click and create a new C# script.

Project Create CSharp Script

Project Create CSharp Script

Name the new file “Fish”

Project Fish CSharp File

Project View Fish CSharp File

If you need to re-name a script, just select it and hit F2.

Windows Only Section (Optional)

If you’re using Windows, I want you to switch your editor to Visual Studio now.  You can use MonoDevelop (the default editor), but the benefits of using Visual Studio make me HIGHLY recommend it.

To switch to Visual Studio, select Edit->Preferences

Preferences Menu

Preferences Menu

Go to the External Tools section and set your External Script Editor to Visual Studio 2015.

Settings - Select Visual Studio

Settings – Select Visual Studio

 

Back to our Code (Mac & Windows)

Now, double click the newly created Fish script.

You should be presented with a code file that looks like this.

using UnityEngine;
using System.Collections;

public class Fish : MonoBehaviour {

 // Use this for initialization
 void Start () {

 }

 // Update is called once per frame
 void Update () {

 }
}

In Unity3D, every Component on a GameObject must inherit from MonoBehavior.  If you don’t know what this means, don’t worry, you’ll pick it up.  What this means for us though is that our Fish script has some default functions we can hook into.  You can see two of these functions in your code now.

  • Start – Any code in here will be called when the GameObject is created in our game.  If it was placed in the Hierarchy (like our fish will be), it’s called when the game starts.
  • Update – Any code we place in here will be called once per Frame.  In a typical game, we’ll have 30-90FPS (Frames per second).  This means that the code here will get called 30-90 times per second.

InputManager

To move the fish, we’ll need to read the players Input.  Because this is such a common thing to do, there’s a very simple way to get it.

Modify your Update function to look like this.

// Update is called once per frame
 void Update () {
   bool pressedFireButton = Input.GetButtonDown("Fire1");
   if (pressedFireButton)
   {
      Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();
      rigidbody.velocity = Vector3.zero;
      rigidbody.AddForce(Vector3.up * 1000);
   }
 }

Now let’s look at the code and see what it’s doing, line by line.

bool pressedFireButton = Input.GetButton("Fire1");

Here, we’re creating a new variable named pressedFireButton.
It’s type is bool – A bool variable can be either true or false.

We’re assigning it a value from our Input system by calling the GetButton method.  The GetButton method takes one parameter which is the name of the button.  We’re passing in the button name “Fire1” and the function will return True if we’ve pressed one of the inputs mapped to it.

Fire1 is a default button in Unity3D that is mapped to many things [Space, Left-Ctrl, Left Click, A button (Xbox), X button (PS), etc].

Checking Conditions

Next we have some conditional code.  This line checks to see if the result of our input check was true.  If so, the code following it in braces {  } will be executed.

if (pressedFireButton)
{
 ... everything in here will execute
}

So if we have pressed the “Fire1” button (ex. tapped space), everything inside the braces will execute.  This will only happen ONCE per press.  You must release and re-press the button for the GetButton(“Fire1”) call to return true.

Handling Physics

The first thing we do inside the braces, is get the RigidBody2D component.  This is the same component you added to the Fish earlier (when it started reacting to gravity).

Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();

The properties we care about are X, Y, & Z.  These are numeric values that represent a measurement on their corresponding axis.

We assign the RigidBody2D of our fish to the variable named “rigidbody”.

The “velocity” of our rigidbody is how fast it’s moving.  It’s measured in a Vector3, which is just a simple data structure containing 3 values (and a couple calculated properties we’ll worry about later).

On the next line, we set the velocity of our rigidbody to Vector3.zero.

rigidbody.velocity = Vector3.zero;

 Vector3.zero is just a shortcut to get a Vector3 with 0 for all 3 of it’s values.

This completely stops our rigidbody.  If it was falling, going up, or in any other direction, this line of code stops it.

So setting the velocity of our rigidbody to Vector3.zero is setting the rate of movement to 0 in all directions.

Adding some Force

Next, we want to add some force and push our Fish upward.

rigidbody.AddForce(Vector3.up * 1000);

AddForce does exactly what the name says.  It takes a single parameter, which is a Vector3.  We pass in Vector3.up, which is just another shortcut to get a Vector3 pointing in the default upward direction.  But before AddForce evaluates the Vector, we multiply it by 1000, so the resulting input is a Vector3 with the values [0, 1000, 0].

You may have already skipped ahead and tried it out.  If not, get in the editor, hit play and try out our input handling.  You should be able to click spaceleft-ctrl, or your mouse’s left-click.  Notice how the fish STOPS, then gets force added.  If we didn’t Stop the fish, you’d have to click very fast just to keep from falling.

It’s too much!

Fish flying too far

Fish flying too far

You may have noticed that the amount of force we’re adding is too much.  Your fish is probably flying way off the top of the screen.  We have a couple ways we could address this problem.  The simplest is to just change that value of 1000 that we used earlier to something smaller.  Go ahead and try that now.  Make sure to SAVE the changed file or Unity3D won’t pick up your changes.

Another way to make these changes is to expose the multiplier we’re using in the Unity3D editor.  Specifically, we’ll exposed it on the Fish component of the Inspector.  To do this, we need to introduce a variable to our Fish class and add a special attribute to it so Unity3D knows we want to edit it.

Change your Fish.cs file to look like this.  Bold parts show the changes.

using UnityEngine;
using System.Collections;

public class Fish : MonoBehaviour {

 [SerializeField]
 private float _upwardForceMultiplier = 100f;

 // Use this for initialization
 void Start () {

 }

 // Update is called once per frame
 void Update () {
   bool pressedFireButton = Input.GetButton("Fire1");
   if (pressedFireButton)
   {
      Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();

      rigidbody.velocity = Vector3.zero;

      rigidbody.AddForce(Vector3.up * _upwardForceMultiplier);
   }
 }
}

What we’ve done here is introduce “_upwardForceMultipler”.  We’ve set the default value to 100f.  The “f” on the end just signifies it’s a floating point value.

Most positional math in Unity3D and other game engines is done with floating point numbers.

Save the changes you’ve made here, then jump back to the editor.

Select the Fish.

You should now see an extra field in the Fish component that matches our variable name.  If you don’t see the component, hit Play, then Stop.  Playing forces a compile, which makes the engine update to your most changes.

Inspector - Upward Force Multiplier

Inspector – Upward Force Multiplier

Now we don’t have to change code to modify our force.  We can simply adjust the number in here until we get a value we’re happy with.  Go ahead and try it now.  Make sure you’re NOT in PLAY mode when making the changes though.

Changes done while you’re in Play mode do not save.  There are good reasons for this that we’ll cover later, but for now, just make sure you’re not playing when you make your changes (or they’ll be lost and you’ll have to do them again).

After a little trial and error, I ended up with 200 for my multiplier.  If you have a different # that’s okay, go with something that feels right to you.  You can always adjust this value later, and now that it’s in the Inspector, you can do it easily.

Continue to: Part 3 – Unity3D Physics & Collisions

We’ll add some Seaweed, learn about Physics & Collisions, and even kill a fish.

Continue reading >
Share

Building Flappy Bird #1 – Unity Intro

Building Flappy Bird in Unity

Unity is a great engine, but like all game engines it has a little learning curve.  This tutorial is designed to take you through the entire process of building a 2D game in Unity that will run on the web, pc/mac, and mobile.  By the time you complete this project, you’ll understand:

  • The different areas of the Unity editor
  • Importing Art
  • Using the Physics system
  • Handling Input
  • Writing a little code (even if you’ve never written code before)

Let’s get started!

Importing the Art Package

In the editor, click Assets, Import Package, Custom Package

Importing a Unity Package

Select Assets->Import Package->Custom Package…

Browse to the Art assets package.  If you don’t have it, you can download it by clicking here.

Import package file list shows of all the files in the package

Import Package File List

You’ll be presented with a file list dialog.  This dialog allows you to select which files in the package you want to import.  By default, all files will be selected.

For now, click “Import”.

Next, focus your attention on the Hierarchy section of the editor.  It should be in the top left corner and contain a single GameObject named “Main Camera”

Hierarchy With Main Camera

Hierarchy With Main Camera

Select the Main Camera by clicking on it.

Hierarchy With Main Camera-Selected

Hierarchy With Main Camera-Selected

Selected GameObjects in your Hierarchy will show blue.  You can select any number of GameObjects at the same time.  For now though, we only have one available to us, so let’s look over to the other side.

Inspector View of "MainCamera"

Inspector View of “MainCamera”

On the right we have the Inspector area.  Here you can see or inspect details about your selected GameObjects.  Notice that the inspector shows 5 components because we’ve selected the default camera object Unity creates for us.   The 2 components you care about today are the Transform and the Camera.

Transform

EVERY GameObject in Unity has a Transform.  The transform controls the objects Position, Rotation, and Scale.

  • Position - The location of the object in the world or relative to it's parent.
  • Rotation - The direction the object is facing.
  • Scale - The size of the object.

Camera

This component allows our game to render.  This is the area we want to modify now.

First, try adjusting the “Background” value and notice how the background changes in the Game View (located in the center) or the Camera Preview.

To change the background, just click on the area showing the current color in the inspector.  The default is blue.

Color Picker

Color Picker

Once you’ve found a water color you like, you need to make sure the Camera Perspective is set to Orthographic.  (It should be by default, but we need to make sure)

Project View

It’s time to put something in our game.  Look to the bottom of your editor where you’ll see the Project area.

Project View

Project View

Browse to the art folder and select the Fish

Project View - Art Folder

Project View – Art Folder

Drag the Fish to the Hierarchy.

You should see the fish in your Hierarchy and in your Scene or Game View.

You can toggle between the 2 views using the tabs, or drag them out to separate them

Scene View Fish

Scene View Fish

Game View Fish

Game View Fish

Play Mode

Now, I want you to hit the Play button and watch what happens!

Game Play Button

Game Play Button

If you’ve followed along so far, nothing should have happened.  The Game View will automatically focus, but nothing should be moving.

Let’s make something happen…

With the Fish selected, hop over to the Inspector.

Click the big Add Component button.

Start typing and find the RigidBody2D.

You can alternatively browse to it under Physics2D.

 

Inspector Add Component

Inspector Add Component

The RigidBody2D component will make our GameObject (the Fish in this instance) interact with the games physics system.  One of those interactions is gravity…

Inspector RigidBody2D

Inspector RigidBody2D

Let’s Play

First, I want you to think for a second.  When you hit “Play” what do you expect will happen?  Say it to yourself, then hit the button and see if you’re right.

If you thought the fish would fall, great.  If not, don’t worry about it.  Because our fish has a RigidBody, it uses gravity (unless Gravity Scale is set to 0).  If there are no other forces acting on the object, the RigidBody will make it fall straight down.

In Part 2, we’ll start handling input and adding some additional force to keep the fish from falling away.

Continue To: Part 2 – Let’s Code!

 

Sign up here to be automatically notified about new posts


Continue reading >
Share
Page 2 of 2