Thursday, January 18, 2018



Today I would like to give you an examples how to create games like flappy bird using unity.  you can play here for the final result of the game flappyfroggame. The starter project you can download here FlappyFrogStarterProject. I use unity 5.6.4, you can use same version as me or later. I made some separated main task for creating this games. here they are :
- scrolling and infinite background
- jumping bird , gravity , Touch Input
- obstacle generator
- collision, game over & restart game

lets make the games.

Scrolling and invinite background


1. Make GameManager
Firstly is make the GameManager object, this object contains the whole game states, instance and manager of the games.
to create new object "command + shift + n".  then create your script GameManager.cs . then attach it on the object.
GameManager.cs

       
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour {
	public GameObject Bird;
	public GameObject GameOver;
	public bool IsGameOver;
	private bool isGameOverAdded;
	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
	void Update () {
		if (IsGameOver) {
			if (!isGameOverAdded) {
				GameObject.Instantiate (GameOver);
				isGameOverAdded = true;
			}
		}
	}

on the GameManager.cs I made field for Bird and GameOver object. and flag for gameover and pop up window of gameover.
on method Update() check the state of current game, if the state is IsGameOver than add GameOverObject to the screen.

2. Make Background Object and animate it
on this step we are gonna create endless moving background. Create 3 new GameObject than assign sprite renderer component, then select  Background.png as Sprite. so now you have 3 background object for endless animating.
Now Create new Script "BackgroundEndlessAnimate.cs" then animate your background here


       

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BackgroundEndlessAnimate : MonoBehaviour {
        //please assign the background object in inspector panel the background
	public GameObject[] Backgrounds;

	public float MoveSpeed;
	public GameManager gameManager;

	//left & right border value got from width of the background
	private float leftBorder = -19.2f;
	private float rightBorder = 38.4f;


	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		if (!gameManager.IsGameOver) {
			//animate background
			Backgrounds[0].transform.position = new Vector3 (Backgrounds[0].transform.position.x - MoveSpeed, 0f,0f);
			Backgrounds[1].transform.position = new Vector3 (Backgrounds[1].transform.position.x - MoveSpeed, 0f,0f);
			Backgrounds[2].transform.position = new Vector3 (Backgrounds[2].transform.position.x - MoveSpeed, 0f,0f);

			//check for border left and assign to right
			foreach(var bg in Backgrounds)
			{

				if (bg.transform.position.x <= leftBorder) {
					bg.transform.position = new Vector3 (rightBorder, 0.0f, 0.0f);
				}
			}
		}

	}

}

Assign this script as component on the GameManager object. then assign the background that you made to the inspector panel. the length of the background object array should 3. and the last is set the value of movespeed, set this to 0.04.

Try Run the Project, if everything going well your background should moving from right to left endlessly.

Jumping Bird and Gravity

1. Gravity System
I made my simple gravity system. Create Bird Object within sprite renderer component and bird.png as sprite. then create script BirdGravity.cs. create public float field for Gravity, then on Update() method write this

       
if (!gameManager.IsGameOver) {
	this.transform.Translate (new Vector3 (0.0f, Gravity, 0.0f));
}
 attach the script to the Bird object then set value of the Gravity on the inspector panel.

2. Add Touch Input object
Create new object called TouchObject, this object will listen your tap on the screen. please add BoxCollider component in the TouchObject and set height and width of collider based on your screen size (the collider cover all area on the screen).

3. Jumping System
Create Jumping Script "BirdMove.cs"

       

public class BirdMove : MonoBehaviour {
	public GameManager GameManager;
	public float JumpValue;

	private const float JUMPTIMEVAL = 8f;
	private bool isJump = false;
	private float jumpTime;
	// Use this for initialization
	void Start () {
		jumpTime = JUMPTIMEVAL;
	}

	void OnMouseDown(){
		if (!GameManager.IsGameOver) {
			isJump = true;
		}
	}

	// Update is called once per frame
	void Update () {
		if (!GameManager.IsGameOver) {
			if (isJump && jumpTime >= 0.0f) {
				GameManager.Bird.transform.Translate (new Vector3 (0.0f, JumpValue, 0.0f));
				jumpTime--;
			} else {
				isJump = false;
				jumpTime = JUMPTIMEVAL;
			}
		}
	}
}

Jumpvalue is for set height of jumping the bird, and the rest jumping logic is in the update() method. assign this script to the TouchObject. then attach the public field to every object.

Try Run the Project, if everything going well the bird will fall down and when you tap in the screen the bird will jump.

Obstacle Generator

lets continue make the obstacle, as we know the flappy bird will game over when the bird hit the green tube in top and bottom. so we will create those object and the generate system.

1. Create obstacle prefabs
create new object called obstacle which contain two of child bottom obstacle and top obstacle and on each child assign boxcollider and rigidbody for component. please set IsTrigger to checked on inspector panel. then save the object as prefabs.

2. Create Generate Obstacle System
create new script "ObstacleGenerator". this script will attached to GameManager object. here the script

       

public class ObstacleGenerator : MonoBehaviour {
	public GameObject Obstacle;
	public int CountGenerate;
	public float DistanceX;
	public float MaxPosY;
	public float MinPosY;
	// Use this for initialization
	void Start () {
		GenerateObstacle ();
	}

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

	void GenerateObstacle()
	{
		for (int i = 0; i < CountGenerate; i++) {
			GameObject newObstacle =  GameObject.Instantiate (Obstacle) as GameObject;
			float posY =  Random.Range (MinPosY, MaxPosY);
			newObstacle.transform.localPosition = new Vector3 (i * DistanceX, posY, -10.0f);
		}
	}
}


and then set this value on the inspector panel of ObstacleGenerator Component.
Obstacle = Obstacle prefab,
CountGenerate = 13,
DistanceX = 4.5,
MaxPosY = 0.8,
MinPosY = -0.5.

3. Animating and moves the Obstacles
create "ObstacleMove.cs" component then attach it on the obstacle prefabs. here the script

       

public class ObstacleMove : MonoBehaviour {

	public float MoveSpeed;
	private const float LEFTBORDER = -19.2f;
	private const float RIGHTBORDER = 38.4f;
	private GameManager gameManager;
	// Use this for initialization
	void Start () {
		gameManager = GameObject.Find ("GameManager").GetComponent ();
	}

	// Update is called once per frame
	void Update () {
		if (!gameManager.IsGameOver) {
			transform.Translate( new Vector3 ((MoveSpeed * -1),0f,0f));

			if (transform.localPosition.x <= LEFTBORDER)
				transform.localPosition = new Vector3 (RIGHTBORDER,transform.localPosition.y,-10.0f);
			
		}

	}
}

the Update() method contains logic for moving the obstacle and give the border/limit when reach the edge of the background, it will move to the far right of the background.
set the  ObstacleMove component of the prefab in inspector panel
MoveSpeed = 0.1

Try Run the Project, if everything going well, the obstacles will generated and automaticly moving from right to left endlessly.


Collision

1. Get the Collision Event
Now lets get the collision event between the Bird and the Obstacle. first thing is create PlayerManager script that used to save the state, or others field needed for the player. this script is used to receive collision state with the obstacle (tube).  on this script we just need GameManager instance. and the concept is when the bird got collide, PlayerManager will set GameManager.IsGameOver to true.
here the script of PlayerManager.cs

       
//assign gameManager here
public GameManager gameManager;

void OnTriggerEnter(Collider col){
        //got collide and then set gameover state
	gameManager.IsGameOver = true;
}
OnTriggerEnter() will invoked when the bird got collide with others object contain collider, since there are no others object contain collider except the obstacle so we can set the gameover state here.

2. Add GameOver Object
The concept is when the user tap this gameover tittle the game will restart. so lets make the GameOver object.
Create New Object which contain Sprite Renderer and gameover.png as sprite. then add Boxcollider on the GameOverObject.
Then make GameOver.cs for restarting the game when tap the object. here the script

       

void OnMouseDown()
{
	SceneManager.LoadScene (0);
	GameObject.Find ("GameManager").GetComponent ().IsGameOver = false;
}


and if you see at the top of this article you can check in GameManager.cs, look at this line

       

void Update () {
	if (IsGameOver) {
		if (!isGameOverAdded) {
			GameObject.Instantiate (GameOver);
			isGameOverAdded = true;
		}
	}
}
this line was indicated that  the GameManager will add GameOver Object when the IsGameOver == true.
Also don't forget to assign the public GameOver object on the GameManager Component.

Try Run the Project, if everything going well, the game over object will show when the bird hit the obstacle (tube).

that's all the for basic games like flappy bird logic tutorial, you can add your scoring system, sound, animating system by yourself. please don't forget to comment if you have questions about this tutorials.

here are the complete project FlappyFrogComplete.


Contact me

Name

Email *

Message *