Programming
Article

Building a Dodger Game Clone in Unity

By Vincent Quarles

In this tutorial, we’ll be building a simple Dodger game in Unity. To see and play the final result, go here.

Dodger clone screenshot

Analyzing the Game

Dodger is a small, simplistic game that doesn’t take much logic to program and can be customized almost endlessly. Dodger only has a few key elements of Gameplay:

  1. Player Input
  2. Player/Enemy Bounds
  3. Random Location Generation
  4. Collision
  5. Lose Condition

Using these five elements we will create a simple Dodger clone. This tutorial assumes you have installed Unity.

Adding the Assets

Create a New Unity2D Project and name it “Dodger” or “DodgerExample”.

Project start screen

First, you will want to download the images from the GitHub page (or right-click and save image as…).

Player and enemy sprites enter image description here

To create folders in Unity you need to Right-Click inside of the Assets Pane and select Create -> Folder. Name your new folder Images, and create 2 more folders named Prefabs and Scripts.

Creating a folder in Unity

After creating your folders you will be able to drag the images you downloaded from the Github page into the Images folder. Select both of the images inside of your Images folder and set their Pixels Per Unit value to 32 and click Apply.

Creating the Player

To add player input we will first have to create a Player game object. You can create a Player game object by dragging the image of the green smiling face into your hierarchy pane. Set the name of the game object to Player and set its Y Position to -3.5.

Creating a player

Modifying Our Camera

If we left the camera like this our sprites would have to use decimal numbers in order to stay just inside the screen like we want. Unity allows us to change the size of the main camera and its background color. Select the camera and click the background color. Set the color to a beautiful shade of blue (R: 0 G : 223 B: 255).

Setting colors for the background

Select the size value of the main camera and set it to 4.4. Finally, inside of the Game pane click on Free Aspect and set the aspect ratio to 4:3.

Changing the aspect ratio

Getting Player Input

We’ll start off our programming by getting player input. In order to get player input we will need to create a new C# Script and name it Player Controller.

Creating a new C# script

Double Click the Script to open it in an IDE. Once the IDE is open add this code to the script:

    //Speed of the Player
    public float speed = 10.0F;

    //bounds of player
    public float leftBound = -5F;
    public float rightBound = 5F;
    public float upBound = 3.5F;
    public float downBound = -3.5F;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //Horizontal Speed
        float movementSpeedX = Time.deltaTime * Input.GetAxis("Horizontal") * speed;        
        //Vertical Speed
        float movementSpeedY = Time.deltaTime * Input.GetAxis("Vertical") * speed;          
        //Player Movement
        transform.Translate(movementSpeedX, movementSpeedY, 0);                         

        //creates bounds around player
        if(transform.position.x > rightBound){
            transform.position = new Vector3(rightBound,transform.position.y,0);
        } else if(transform.position.x < leftBound){
            transform.position = new Vector3(leftBound,transform.position.y,0);
        }

        if(transform.position.y > upBound){
            transform.position = new Vector3(transform.position.x,upBound,0);
        } else if(transform.position.y < downBound){
            transform.position = new Vector3(transform.position.x,downBound,0);
        }
    }

Note: the actual values for the bounds may vary. If this is the case add the appropriate value to the bound variables

Add the Player Controller script to the Player game object in the hierarchy by dragging it from the Assets pane onto the Player game object. If you run the game and try to control the Player using the arrow keys you will see the player move on screen.

Fine tuning the player object

The Enemy

Next we will need to create the enemy. In order to create the enemy you will need to drag the angry green block into the hierarchy pane. Go ahead and name the game object Enemy. Click under the game object’s name where it says Untagged then click “Add Tag”. Create a tag named “Enemy”, and give the Enemy game object this tag. Select the Player game object and give the it the tag “Player”.

The enemy is untagged

Tagging the enemy

Now that we have the tags set which will tell the difference between the Player and the Enemy, we can start coding the enemy’s behavior. Open the Scripts folder in the Assets pane and create a new C# script named “EnemyController”. Add the EnemyController script to the Enemy game object. Open the script in your IDE and type this into your script:

    //speed of Enemy
    public float speed = 8F;    

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //Movement of Enemy
        transform.Translate(0, -speed * Time.deltaTime, 0);         
    }

Adding Collision

Inside of Unity select the Player game object. In the Player game object’s Inspector pane click the Add Component button, search for “Circle Collider 2D”, and add it to the Player game object. Do the same again, except search for “Rigidbody 2D” and add it to the Player game object. On the Rigidbody 2D set the values to the same as the image below.

Adding a collider enter image description here

Next select the Enemy game object, and inside of its Inspector pane click on the Add Component button. Search for “Box Collider 2D” and add it to the Enemy game object. Check “Is Trigger” inside of the menu for the Enemy game object’s Box Collider 2D.

Open the EnemyController script inside of your IDE and under the Update method type:

void OnTriggerEnter2D(Collider2D other){

        //Checks if other gameobject has a Tag of Player
        if(other.gameObject.tag == "Player"){
            //Pauses gameplay
            Time.timeScale = 0;         
        }
}

Randomly Spawning the Enemy

Inside of Unity drag the Enemy game object in to the Prefabs folder inside of your Assets pane. Delete the Enemy that is inside of the hierarchy since we will be randomly generating the location of all of the spawned enemies. Right click inside of the hierarchy pane and select “Create Empty”. Name the empty game object “EnemySpawner” and sets its Y position to 6. Inside of the scripts folder create a new C# script named “EnemySpawnerController” and open it inside of your IDE.

Inside of your EnemySpawnerController script type:

    //rate at which enemies spawn
    public float spawnRate = 1;     

    //enemy prefab
    public GameObject enemy;    

    //bounds of spawner
    public float leftBound = -5F;
    public float rightBound = 5F;


    // Use this for initialization
    void Start () {
        //call SpawnEnemy based on spawnRate
        InvokeRepeating("SpawnEnemy", 1, spawnRate);        
    }

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

    }

    void SpawnEnemy(){
        //a clone of the enemy prefab
        GameObject enemyClone;  

        //spawns enemyClone at this location and rotation   
        enemyClone = Instantiate(enemy, this.transform.position, this.transform.rotation) as GameObject;        

        //randomly moves spawner along x axis
        float x = Random.Range(leftBound, rightBound);
        transform.position = new Vector3(x,this.transform.position.y, 0);
    }

Inside of Unity, drag the Enemy prefab (from inside the Prefabs folder) onto the Enemy value under the Enemy Spawner Controller menu inside of the EnemySpawner Inspector pane. Select the EnemySpawner in the Hierarchy pane and hit COMMAND+D (or right click the game object and select duplicate) to duplicate the game object. Name the new EnemySpawner game object to “EnemySpawner 2” and set its X position to 2. Select the EnemySpawner game object from the hierarchy pane and set its X position to 2.

Adding Basic UI

Inside of the hierarchy pane, right-click and select “Create Empty”. Set the new game object’s name to “UIManager”. In your scripts folder create a new C# script and name it “UIManager”. Open the script in your IDE and type:

// Use this for initialization
void Start () {
    Time.timeScale = 1;
}

//Reloads the Level
public void Reload(){
        Application.LoadLevel(Application.loadedLevel);
}

Inside of Unity, in the top menu, select GameObject -> UI -> Button. Name the new button “Refresh Button” and set its X position to 202 and its Y position to 196. Hit the dropdown arrow next to Refresh Button in the the hierarchy pane and select the Text game object. Set the game objects text value to “Refresh”. Select the Refresh Button from the hierarchy pane and in its button Menu click the plus at the end of the On Click () menu. Set the On Click method’s game object to the UIManager game object and set the method to UIManager -> Reload.

Adding the refresh game button

Finishing Up

Create a “Scenes” folder in the Assets pane. Save our current scene as “MainLevel” and it to the scenes folder. From the top menu select File -> Build Settings and drag the MainLevel scene from the Assets pane into the Build Settings menu or hit “Add Current” in the menu. Finally, build the game to either PC, Mac, or Web and have fun playing.

Conclusion

This short but to-the-point tutorial went through the exact steps of creating a clone of the popular Dodger game in Unity. Hopefully, you liked it and are craving for more Unity content – it’s coming soon, we promise! Feedback? Comments? Leave them below!

You can download the full project on GitHub.

  • http://careersreport.com Pauline Gary

    Allow me to show #you a suberb way to earn a lot of extra money by finishing basic tasks from your house for few short hours a day — See more info by visiting >MY____$DISQUS$____ID;}

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Front-end, once a week, for free.