Coin Run - A Simple Retro Arcade Game For Android/IOS

Operating System
In this tutorial I will show you on how to create a popular game like “Pac man” using a Unity Game Engine and a C# script. Unity is an all-purpose game engine that supports 2D and 3D graphics, drag and drop functionality and scripting through C#. Unity Script is a proprietary scripting language which is syntactically similar to JavaScript. Unity is notable for its ability to target games for multiple platforms. So let's get started and see for ourselves.

Getting Started – Creating Project

First you will need to download & install Unit Game Engine, here's the link for the https://store.unity.com/. After the Unity Game Engine is installed, open the unity game engine then we will get started. Here is the interface of the unity game engine when open. tut1 Click "New", and then enter the project name "Coin Run ". After entering the name click the 2D button because the game will be make is in 2D environment, and after that place it into your designated directory. tut2 This is how the Unity Game Engine Environment looks like. tut3 Now we are now ready to create our game.

Setting up Editor – Game Resolution, Changing Platform

Game Resolution

First thing to do is to set up our Game resolution, to do that click the game tab then go to "Free Aspect" it is just below of Game tab. Then click the add button (the one that looks like +) and enter the value of each properties. For Width just make it "1280" so that we can have a great resolution for our game, then for Height leave it just "720". tut4

Changing the Platform

Under the File, Click Build Setting and select Android, and then click Switch Platform. tut5

Categorizing Assets

We will now then categorize our needed assets, so that we can avoid misplaces and hard to find files. *Animation - This is where we put all our animator controller and animations *Fonts - This where all our fonts is located *Scenes - This is where we put all our scene objects. *Scripts - This is where we put all our scripts. *Sounds - The directory for our audio files. *Sprites - All our images and sprites can be located here. Note: All our needed assets are already include in the download file. To get the assets just click below the download button.

Creating Main Menu – Creating Scenes, Controllers, Main Menu UI, and Slicing Sprites

Creating Scenes

In the Unity environment you will notice an "Untitled" object in the Hierarchy area. That is the name of the scenes by default, to change it just simply press ctrl + s and save it as "Main Menu" tut6

Creating Controllers

Now that we have the main menu scene we will now create Controllers for the game. The Controllers are game objects that handle some methods that be needed in the game later. To do that just click "GameObject" tab, then a drop down will show up. Then in the sub menu click "Create Empty", a GameObject will appear in the Hierarchy. tut7 Before working on the GameObject make sure to reset its transform to avoid conflict in the future. tut8 Rename your GameObject as "Game Controller", then go to the Scripts directory create a new folder called Game Controllers. Right click the mouse button and select create then choose C# script. tut9 Save it as "GameController". The Game Controller handles all the save data of our game. Note: To avoid script error make sure the name of your script has no space, because C# is white space sensitive. And make sure to save all Controllers inside the Game Controllers folder to avoid misplaced. Open you’re newly created Script; you notice that there is already a block code in the script. By default the unity engine already created that part to make the developer at ease.
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class GameController : MonoBehaviour {
  6.  
  7.         // Use this for initialization
  8.         void Start () {
  9.                
  10.         }
  11.        
  12.         // Update is called once per frame
  13.         void Update () {
  14.                
  15.         }
  16. }
Now that everything is ready, we will now do our coding thing. First import these important modules.
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. Then write these blocks of code inside the GameController class.
  5. public static GameController instance;
  6.  
  7. public bool isGameStartedFirstTime;
  8. public bool isMusicOn;
  9. public bool isGameStartedInMainMenu;
  10.  
  11. public int highScore;
  12. public int currentScore;
  13. public int currentLives;
  14. public int currentLevel = 1;
  15.  
  16. private GameData data;
  17.  
  18. void Awake(){
  19.     MakeInstance ();
  20.     InitializeGameVariables ();
  21. }
  22.  
  23.     // Use this for initialization
  24. void Start () {
  25.        
  26. }
  27.    
  28.  
  29.  
  30. // Update is called once per frame
  31. void Update () {
  32.        
  33. }
  34.  
  35. void MakeInstance(){
  36.    if (instance != null) {
  37.       Destroy (gameObject);
  38.    } else {
  39.       instance = this;
  40.       DontDestroyOnLoad (gameObject);
  41.    }
  42. }
  43.  
  44. void InitializeGameVariables(){
  45.    Load ();
  46.  
  47.    if (data != null) {
  48.       isGameStartedFirstTime = data.GetIsGameStartedFirstTime ();
  49.    } else {
  50.       isGameStartedFirstTime = true;
  51.    }
  52.  
  53.    if (isGameStartedFirstTime) {
  54.       isMusicOn = true;
  55.       highScore = 500;
  56.       isGameStartedFirstTime = false;
  57.       data = new GameData ();
  58.       data.SetIsGameStartedFirstTIme (isGameStartedFirstTime);
  59.       data.SetHighScore (highScore);
  60.       data.SetIsMusicOn (isMusicOn);
  61.  
  62.       Save ();
  63.  
  64.       Load ();
  65.    } else {
  66.       isMusicOn = data.GetIsMusicOn();
  67.       highScore = data.GetHighScore ();
  68.       isGameStartedFirstTime = data.GetIsGameStartedFirstTime ();
  69.    }
  70. }
  71.  
  72. public void Save(){
  73.    FileStream file = null;
  74.  
  75.    try{
  76.       BinaryFormatter bf = new BinaryFormatter();
  77.       file = File.Create(Application.persistentDataPath + "/data.dat");
  78.       if(data != null){
  79.          data.SetIsGameStartedFirstTIme(isGameStartedFirstTime);
  80.          data.SetIsMusicOn(isMusicOn);
  81.          data.SetHighScore(highScore);
  82.          bf.Serialize(file, data);
  83.       }
  84.    }catch(Exception e){
  85.       Debug.LogException (e, this);
  86.    }finally{
  87.       if(file != null){
  88.          file.Close ();
  89.       }
  90.    }
  91. }
  92.  
  93. public void Load(){
  94.    FileStream file = null;
  95.  
  96.    try{
  97.       BinaryFormatter bf = new BinaryFormatter();
  98.       file = File.Open(Application.persistentDataPath + "/data.dat", FileMode.Open);
  99.       data = bf.Deserialize(file) as GameData;
  100.    }catch(Exception e){
  101.       Debug.LogException (e, this);
  102.    }finally{
  103.       if(file != null){
  104.          file.Close ();
  105.       }    
  106.    }
  107. }
  108.  
  109. [Serializable]
  110. class GameData{
  111.  
  112. private bool isGameStartedFirstTime;
  113. private bool isMusicOn;
  114.  
  115. private int highScore;
  116.  
  117. public void SetIsGameStartedFirstTIme(bool isGameStartedFirstTime){
  118.    this.isGameStartedFirstTime = isGameStartedFirstTime;
  119. }
  120.  
  121. public bool GetIsGameStartedFirstTime(){
  122.    return this.isGameStartedFirstTime;
  123. }
  124.  
  125. public void SetIsMusicOn(bool isMusicOn){
  126.    this.isMusicOn = isMusicOn;
  127. }
  128.  
  129. public bool GetIsMusicOn(){
  130.    return this.isMusicOn;
  131. }
  132.  
  133. public void SetHighScore(int highScore){
  134.    this.highScore = highScore;
  135. }
  136.  
  137. public int GetHighScore(){
  138.    return this.highScore;
  139. }
To make this work attach the script to the Game Controller object as a component, by dragging this to the Game Controller Inspector or by clicking add component then go to script and locate the GameController script.

Creating Music Controller

The Music Controller handles the background sounds of the game, this is where you put your game sound clip as an array. Just like what you did on the Game Controller, create a new GameObject then name it as "Music Controller". Then create a new C# script name it as "MusicController". Note: All the needed sounds are already in the Sounds folder. Inside the Music Controller script, create a certain variable that we will use for our sounds.
  1. public static MusicController instance;
  2.  
  3. public AudioClip backgroud;
  4. public AudioClip gameplay;
  5. public AudioClip coinRush;
  6. public AudioClip death;
  7. public AudioClip start;
  8. public AudioClip bite;
  9.  
  10. [HideInInspector]
  11. public AudioSource audioSource;
In the start method assigns the “audioSource” variable to its AudioSource component;
  1. audioSource = GetComponent<AudioSource> ();
After that we will need to create an instance of the script; this will prevent the script to stop working when going to other scenes.
  1. void CreateInstance(){
  2.    if(instance != null){
  3.       Destroy (gameObject);
  4.    }else{
  5.       instance = this;
  6.       DontDestroyOnLoad (gameObject);
  7.    }
  8. }
Then create an awake method, a built in method of unity that call any script first when the game started, call the CreateInstance() inside the awake method.
  1. void Awake(){
  2.    CreateInstance ();
  3. }
Then write this certain methods to make the sounds work perfectly in the game
  1. public void PlayMainMenuBg(){
  2.    if(backgroud){
  3.       audioSource.clip = backgroud;
  4.       audioSource.loop = true;
  5.       audioSource.Play ();
  6.    }
  7. }
  8.  
  9. public void PlayGameplaySound(){
  10.    if(gameplay){
  11.       audioSource.clip = gameplay;
  12.       audioSource.loop = true;
  13.       audioSource.Play ();
  14.    }
  15. }
  16.  
  17.     public void PlayCoinRush(){
  18.         if(coinRush){
  19.             if(audioSource.isPlaying){
  20.                 audioSource.clip = coinRush;
  21.                 audioSource.loop = true;
  22.                 audioSource.Play ();
  23.             }
  24.         }
  25.     }
  26.  
  27.     public void PlayDeathSound(){
  28.         if(death){
  29.             if(!audioSource.isPlaying){
  30.                 audioSource.clip = death;
  31.                 audioSource.loop = false;
  32.                 audioSource.Play ();
  33.             }
  34.         }
  35.     }
  36.  
  37.     public void  PlayStartSound(){
  38.         if(death){
  39.             audioSource.clip = start;
  40.             audioSource.loop = false;
  41.             audioSource.Play ();
  42.         }
  43.     }
  44.  
  45.     public void StopAllSounds(){
  46.         if(audioSource.isPlaying){
  47.             audioSource.Stop ();
  48.         }
  49.     }
Next you need to attach the script to the Music Controller as a component; it is just the same like you did on Game Controller. After that add a new component called AudioSource. It manages the sounds of the game, and uncheck the Play On Wake because it will be done automatically with the script. Then from the sounds directory drag all the sound into the AudioClips array. tut10

Creating Main Menu Controller

The Main Menu Controller is the one that handles the option settings and where you start the game, and also trigger some events that necessary needed in the game. To do this just simply creates a new GameObject name it as Main Menu Controller. Create a script and name it as MainMenuController. Inside the Main Menu Controller script, create a certain variable that we will use. Write this code inside the Main Menu Controller class.
  1. public GameObject exitPanel;
Then add this several methods to your script.
  1. // Use this for initialization
  2. void Start () {
  3.    if (GameController.instance.isMusicOn) {
  4.       MusicController.instance.PlayMainMenuBg ();    
  5.    } else {
  6.       MusicController.instance.StopAllSounds ();
  7.    }
  8. }
  9.    
  10.     // Update is called once per frame
  11. void Update () {
  12.    if(Input.GetKeyDown(KeyCode.Escape)){
  13.       if (!exitPanel.activeInHierarchy) {
  14.          exitPanel.SetActive (true);
  15.       } else {
  16.          exitPanel.SetActive (false);
  17.       }
  18.    }
  19. }
  20.        
  21.  
  22. public void StartButton(){
  23.    if(GameController.instance != null){
  24.       GameController.instance.isGameStartedInMainMenu = true;
  25.    }
  26.  
  27.    SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 1);
  28. }
  29.  
  30. public void YesButton(){
  31.    Application.Quit ();
  32. }
  33.  
  34. public void NoButton(){
  35.     exitPanel.SetActive (false);
  36. }
Note: When using a UI Components in the script you will just need to import some modules.
  1. using UnityEngine.UI;
And for loading some scenes you will also need this
  1. using UnityEngine.SceneManagement;

Slicing Sprites

When slicing the sprite sheet into a several images you need to select first your image, then in Sprite Mode choose Multiple after that click Sprite Editor. A new Pop up window will appear from here click the Slice on the menu bar, and then Slice. It will automatically slice the sheet of a sprite. tut14 tut15 Note: All the needed sprite in the game is already in Sprites folder.

Main Menu UI

The Main Menu UI is a GameObject that hold a several Children component. To Create a UI click the GameObject menu then choose UI then Image. You notice that it automatically create a UI Canvas then your image as a child of it, and also a new object called EventSytem. EventSystem handle the entire trigger event such as when click the buttons, or toggles etc. tut11 Then rename Canvas as "Main Menu UI", and also Image as "Background". In the Main Menu UI set the values same as the image shown below. tut12 To make the Background Image locate your sprite from the Game UI directory then add it to the Background GameObject as a component. tut13 Now that we have the image we will now add a button, just like what you did on the image select UI then choose Button. Now that your sprites are ready remove the child text of button, then add a sprite to their components. Then attach the “Main Menu Controller” script to the Start Button RuntimeController. tut16

Main Menu UI - Exit Panel

We will now create the Exit Panel, exit panel take care of the prompt that closes the app. Create a panel then name it as "Exit Panel Background". And create another panel by just right clicking the GameObject then set its name as "Exit Panel" and set the components as shown in the inspector below.

Exit Panel Background

tut17

Exit Panel

tut18 Then add a several children (Text, Buttons) for the Exit Panel. Then set the values of each component as shown below.

Text

tut19

Buttons

tut20

Creating Animations and Gameplay UI

Creating Animations

In the Animations folder create new folders then rename them as follow: Coins, Player, and Enemies. This is where we will store our animations that we will use to animate the sprites. Player Animation First thing to do is to locate the sprite of the player and drag it in the Scene View.
  1. Click the sprite and rename it as Player.
  2. Open the Animation Pane
  3. Click Create New Clip name it as Player Move, and save the animation in the Player folder.
  4. Drag the rest of the sprite in the Animation Pane. Set a 5 seconds delay to each sprite to have a better animation.
  5. Click Play to animate the sprite. tut21
  6. After you save the animation the animation. Locate the Player Death sprite and name it Player Death, then drag it to Scene View.
  7. Do the same as what you did on the other Animation, save it in the Player folder, and then delete the GameObject Player Death afterward.
Note: We deleted the Player Death GameObject because we just only needed the Runtime Animator Controller of the animation sprites. We will call it later via CSharp script to toggle each animation. Enemy Animation First go to the Enemies Folder and create new folders, and then name them as follow: Afraid, Pale, Green Enemy, Purple Enemy, Red Enemy, and Yellow Enemy. First locate the enemy sprite and drag it in the Scene View.
  1. Click the sprite and rename it as Red Enemy, this will be the base sprite.
  2. Drag again another sprite and rename it as Red Right, the name is based on the sprite position and this will act as the animation for the Red Enemy. tut22
  3. Open the Animation Pane.
  4. Drag the rest of the sprite in the Animation Pane that looks exactly the Red Right sprite. Set a 12 seconds delay to each sprite to have a better animation.
  5. Click Create New Clip name it as Red Right to indicate the sprite name, and save the animation in the Red Enemy folder.
  6. Click Play to animate the sprite. tut23
  7. Do the same to the other Red Enemy sprite and save it in the Red Enemy folder, and then delete the GameObjects afterward. tut24a
  8. For the other enemies just do the same as what you did on the Red Enemy, and also for the Afraid and Pale.
Coin Animation First locate the coin sprite and drag the Silver Coin in the Scene View.
  1. Click the sprite and name it as Coin.
  2. Open the Animation Pane.
  3. Click Create New Clip name it as Coin Animation, and save the animation in the Coins folder.
  4. Drag the rest of the sprite in the Animation Pane, and set a 5 seconds delay to each sprite to have an accurate animation. tut24
  5. Do the same to the other Coins sprite and save it in the Coins folder as Gold Coin.

Creating the Gameplay UI

First thing to do is to adjust our camera set the value of its components as show below tut25 Note: We configure the Camera because our game itself is a grid base point. Now that we’re finished setting up the Camera, we will now create the background of the Game. Just locate the sprite in the Sprites folder and drag the Maze sprite in the Scene View. Set its Transform Position, to X = 13.5 and for Y = 15. tut26 Then create a Canvas UI GameObject and rename it as Gameplay UI. After that create an UI Image, then rename it as Background and drag the sprite from the Game UI folder as the Source Image. Set its components values as shown in the image. tut27 In the Background create a UI GameObject as shown in the image. tut28 Afterwards, create an UI Button in Gameplay UI anchor the Transform in the upper right corner. While holding the Alt and Shift, click the anchor button. And also create a Text UI and rename it as Ready, this will the preparation time for the Player to move. tut29 The result will look like these: tut30

Creating the Intersection and Non Intersection

We will now create the pathway to move the Player around the maze freely. First thing to do is to place the coin in the vacant space of the maze. The position must be a one point away from each coin, and also include at least 4 Gold Coin. tut31 Next we need to divide the Coins into two GameObject the: Intersect and Non Intersect. Put all the Coins that is possible to make an intersection between the other Coins to the Intersect GameObject, and the rest that has no intersection goes to Non Intersection GameObject. tut32 Now that we have divided the Coins we will now create the script that handles the Intersection that the Player passes through from Intersect to Intersect. To do that go to the Scripts folder and create a script namely Intersect. Write these variables inside the Intersect class
  1. public bool isTeleporter;
  2. public bool isHouseEntrance;
  3. public bool isHouse;
  4. public GameObject gateWay;
  5. public Intersect[] nearestIntersect;
  6. public Vector2[] possibleDirection;
Then Call these blocks of code in the Start method
  1. possibleDirection = new Vector2[nearestIntersect.Length];
  2.         for(int i = 0; i < nearestIntersect.Length; i++){
  3.             Intersect intersection = nearestIntersect [i];
  4.             Vector2 temp = intersection.transform.localPosition - transform.localPosition;
  5.             possibleDirection [i] = temp.normalized;
  6.         }
After that attach the script to each Coins that are in the Intersect GameObject.
  1. Drag now the Coins that can be Intersect to the other Coins in the Intersect script. tut33
  2. Then duplicate one of the Coins in the Intersect then place it as shown in the image, then remove the Sprite Renderer component. tut34 Note: To make the GameObject like in the image above, just click the object beside the GameObject name. tut35
  3. Next duplicate again another Coins then place it like in the image below. Make sure the distance of each intersection is one point away from each other. tut36

    Note: Drag again the coins that can Intersect to others Coins in the Intersect script, and then remove the Sprite Renderer component in the GameObjects.

  4. Check the In House Entrance in the Intersect script. tut37
  5. Also check the In House in the Intersect script that is inside the maze tut38
  6. Clone again another Coin and place it in the entrance of the maze to make a passage way to other side. And check the Is Teleporter to make the Teleporter travel to the other side. tut39 Note: Make sure to drag the GameObject that has possible intersection in the Intersect script to move the characters or else they will not move properly.
  7. Create a script namely Coins and attach it to Coins, write these certain variables inside the Coins class.
    1. public bool silverCoin;
    2. public bool goldCoin;
    3. public bool didGet;
  8. Check Silver Coin if the color of coin is silver or check Gold Coin if the color of coin is gold. tut40

Creating Player Controller

Now that we’re done with the Intersection, let’s now proceed by creating the Player Controller. Go to the script directory then create a new script namely PlayerController. Write these variables inside the PlayerController class to get started:
  1. public Vector2 position;
  2. public float speed = 6f;
  3. public Sprite idle;
  4. public Sprite standby;
  5. public AudioClip getCoin;
  6. public bool canMove;
  7. public RuntimeAnimatorController moveAnimation;
  8. public RuntimeAnimatorController deathAnimation;
  9. public Button leftButton, rightButton, downButton, upButton;
  10.  
  11. private AudioSource audioSource;
  12. private Vector2 direction;
  13. private Vector2 nextMove;
  14. private float flipPosition;
  15. private Intersect currentPosition, previousPosition, targetPosition;
  16. private Intersect startingPosition;
Note: Make sure to import the module using UnityEngine.UI so that we can assign variables that using UI component. Then write these blocks of code:
  1. // Use this for initialization
  2. void Start () {
  3. InitializePlayerVariables ();
  4. }
  5.  
  6. public void Restart(){
  7. canMove = true;
  8. transform.GetComponent<Animator> ().runtimeAnimatorController = moveAnimation
  9. transform.GetComponent<Animator> ().enabled = true;
  10. transform.GetComponent<SpriteRenderer> ().enabled = true;
  11. transform.position = startingPosition.transform.position;
  12. currentPosition = startingPosition;
  13. direction = Vector2.left;
  14. position = Vector2.left;
  15. nextMove = Vector2.left;
  16.  
  17. ChangePosition (direction);
  18. }
  19.  
  20. // Update is called once per frame
  21. void Update () {
  22. if (canMove) {
  23. PlayerMovement ();
  24. }
  25. }
  26.  
  27. void InitializePlayerVariables(){
  28. audioSource = GetComponent<AudioSource> ();
  29. Intersect intersect = GetIntersectPosition (transform.localPosition);
  30. startingPosition = intersect;
  31. if(intersect != null){
  32. currentPosition = intersect;
  33. }
  34. direction = Vector2.left;
  35. position = Vector2.left;
  36. ChangePosition (direction);
  37. }
  38.  
  39. void PlayerMovement(){
  40. PlayerInput ();
  41. Move ();
  42. UpdatePosition ();
  43. UpdateAnimationState ();
  44.         GetCoins ();
  45. }
  46.  
  47. void PlayerInput(){
  48. if(Application.platform == RuntimePlatform.Android){
  49. TouchScreen ();
  50. }else if(Application.platform == RuntimePlatform.WindowsEditor){
  51. KeyboardInput ();
  52. }
  53. }
  54.  
  55. void KeyboardInput(){
  56. if(Input.GetKeyDown(KeyCode.LeftArrow)){
  57. ChangePosition (Vector2.left);
  58. }else if(Input.GetKeyDown(KeyCode.RightArrow)){
  59.                 ChangePosition (Vector2.right);
  60. }else if(Input.GetKeyDown(KeyCode.UpArrow)){
  61.                 ChangePosition (Vector2.up);
  62. }else if(Input.GetKeyDown(KeyCode.DownArrow)){
  63.                 ChangePosition (Vector2.down);
  64. }
  65. }
  66.  
  67. void TouchScreen(){
  68. leftButton.onClick.AddListener (() => ChangePosition (Vector2.left));
  69.         rightButton.onClick.AddListener (() => ChangePosition (Vector2.right));
  70.         upButton.onClick.AddListener (() => ChangePosition (Vector2.up));
  71.         downButton.onClick.AddListener (() => ChangePosition (Vector2.down));
  72. }
  73.  
  74. void ChangePosition(Vector2 direction){
  75. if(direction != this.direction){
  76. nextMove = direction;
  77. }
  78.  
  79.         if(currentPosition != null){
  80. Intersect moveToIntersect = CanMove (direction);
  81. if(moveToIntersect != null){
  82.                 this.direction = direction;
  83.                 targetPosition = moveToIntersect;
  84.                 previousPosition = currentPosition;
  85.                 currentPosition = null;
  86.         }
  87. }
  88. }
  89.  
  90. void Move(){
  91. if(targetPosition != currentPosition && targetPosition != null){
  92. if(nextMove == direction * -1){
  93. direction *= -1;
  94.         Intersect temp = targetPosition;
  95.         targetPosition = previousPosition;
  96.         previousPosition = temp;
  97. }
  98.  
  99.         if (CheckDetection ()) {
  100.                 currentPosition = targetPosition;
  101.                 transform.localPosition = currentPosition.transform.position;
  102. GameObject nextTeleporter = GetTeleporter (currentPosition.transform.position);
  103.  
  104.         if(nextTeleporter != null){
  105. transform.localPosition = nextTeleporter.transform.position;
  106. currentPosition = nextTeleporter.GetComponent<Intersect> ();
  107. }
  108.  
  109. Intersect moveToIntersect = CanMove (nextMove);
  110.  
  111. if (moveToIntersect != null) {
  112. direction = nextMove;
  113. }
  114.  
  115. if (moveToIntersect == null) {
  116. moveToIntersect = CanMove (direction);
  117. }
  118.  
  119. if (moveToIntersect != null) {
  120. targetPosition = moveToIntersect;
  121.         previousPosition = currentPosition;
  122.         currentPosition = null;
  123. } else {
  124. direction = Vector2.zero;
  125. }
  126. } else {
  127. transform.localPosition += (Vector3)(direction * speed) * Time.deltaTime;
  128.  
  129. }      
  130. }
  131. }
  132.  
  133. void MoveToIntersect(Vector2 direction){
  134. Intersect moveToIntersect = CanMove (direction);
  135.         if(moveToIntersect != null){
  136.                 transform.localPosition = moveToIntersect.transform.position;
  137.                 currentPosition = moveToIntersect;
  138.         }
  139. }
  140.  
  141. void UpdatePosition(){
  142. if(direction == Vector2.left){
  143.                 position = Vector2.left;
  144.                 transform.localScale = new Vector3(1, 1, 1);
  145.                 flipPosition = transform.localScale.x;
  146.                 transform.localRotation = Quaternion.Euler (0, 0, 0);
  147.         }else if(direction == Vector2.right){
  148.                 position = Vector2.right;
  149.                 transform.localScale = new Vector3(-1, 1, 1);
  150.                 flipPosition = transform.localScale.x;
  151.                 transform.localRotation = Quaternion.Euler (0, 0, 0);
  152.         }else if(direction == Vector2.up){
  153.                 position = Vector2.up;
  154.                 if (flipPosition == 1) {
  155.                         transform.localScale = new Vector3(1, 1, 1);
  156.                         transform.localRotation = Quaternion.Euler (0, 0, -90);
  157.                 } else if(flipPosition == -1) {
  158.                         transform.localScale = new Vector3(-1, 1, 1);
  159.                         transform.localRotation = Quaternion.Euler (0, 0, 90);
  160.         }
  161.  
  162.  
  163.         }else if(direction == Vector2.down){
  164.                 position = Vector2.down;
  165.                 if(flipPosition == 1){
  166.                         transform.localScale = new Vector3(1, 1, 1);
  167.                         transform.localRotation = Quaternion.Euler (0, 0, 90);
  168.                 }else if(flipPosition == -1){
  169.                         transform.localScale = new Vector3(-1, 1, 1);
  170.                         transform.localRotation = Quaternion.Euler (0, 0, -90);
  171.                 }
  172.  
  173.  
  174.         }
  175. }
  176.  
  177. void UpdateAnimationState(){
  178. if (direction == Vector2.zero) {
  179. GetComponent<Animator> ().enabled = false;
  180.                 GetComponent<SpriteRenderer> ().sprite = idle;
  181.         } else {
  182.                 GetComponent<Animator> ().enabled = true;
  183.         }
  184. }
  185.  
  186. public void GetBite(){
  187.         if(GameController.instance != null && MusicController.instance != null){
  188.                 if(GameController.instance.isMusicOn){
  189.                         audioSource.PlayOneShot (MusicController.instance.bite);
  190.                 }
  191.         }
  192. }
  193.  
  194. void GetCoins(){
  195.         GameObject newObj = GetPathPosition (transform.position);
  196.         if(newObj != null){
  197.         Coins coin = newObj.GetComponent<Coins> ();
  198.                 if(coin != null){
  199.                 if(!coin.didGet && (coin.silverCoin || coin.goldCoin)){
  200.                         newObj.GetComponent<SpriteRenderer> ().enabled = false;
  201.                         coin.didGet = true;
  202.                         GameplayController.instance.coins++;
  203.                         if(GameController.instance != null){
  204.                                 GameController.instance.currentScore += 10;
  205.                                 }
  206.                        
  207.  
  208.                         if(coin.goldCoin){
  209.                         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  210.  
  211.                                         foreach(GameObject enemy in enemies){
  212.                           enemy.GetComponent<EnemyController> ().StartAfraidMode ();
  213.                         }
  214.                         }
  215.  
  216.                     if (GameController.instance != null && MusicController.instance != null) {
  217.                         if (GameController.instance.isMusicOn) {
  218.                             audioSource.PlayOneShot (getCoin);
  219.                         }
  220.                     }
  221.                        
  222.                 }
  223.                 }
  224.         }
  225. }
  226.  
  227. private Intersect CanMove(Vector2 direction){
  228.         Intersect moveToIntersect = null;
  229.         for(int i = 0; i < currentPosition.nearestIntersect.Length; i++){
  230.             if(currentPosition.possibleDirection[i] == direction){
  231.                 moveToIntersect = currentPosition.nearestIntersect [i];
  232.                 break;
  233.             }
  234.         }
  235.  
  236.         return moveToIntersect;
  237. }
  238.  
  239. private GameObject GetPathPosition(Vector2 position){
  240.         int x = Mathf.RoundToInt (position.x);
  241.         int y = Mathf.RoundToInt (position.y);
  242.    
  243.         GameObject path = GameplayController.instance.gameSize[x, y];
  244.  
  245.         if(path != null){
  246.             return path;
  247.         }
  248.  
  249.         return null;
  250. }
  251.  
  252.     private Intersect GetIntersectPosition(Vector2 position){
  253.         GameObject path = GameplayController.instance.gameSize [(int)position.x, (int)position.y];
  254.         if (path != null) {
  255.             return path.GetComponent<Intersect>();
  256.         }
  257.  
  258.         return null;
  259.     }
  260.  
  261.     private bool CheckDetection(){
  262.         float intersectToTarget = LengthFromIntersect (targetPosition.transform.position);
  263.         float intersectToCurrent = LengthFromIntersect (transform.localPosition);
  264.  
  265.         return intersectToCurrent > intersectToTarget;
  266.     }
  267.  
  268.     private float LengthFromIntersect(Vector2 targetPosition){
  269.         Vector2 temp = targetPosition - (Vector2)previousPosition.transform.position;
  270.         return temp.sqrMagnitude;
  271.     }
  272.  
  273.     private GameObject GetTeleporter(Vector2 position){
  274.         GameObject path = GameplayController.instance.gameSize [(int)position.x, (int)position.y];
  275.         if(path != null){
  276.             if (path.GetComponent<Intersect> () != null) {
  277.                 if (path.GetComponent<Intersect> ().isTeleporter) {
  278.                     GameObject nextTeleporter = path.GetComponent<Intersect> ().gateWay;
  279.                     return nextTeleporter;
  280.                 }
  281.             }
  282.         }
  283.  
  284.         return null;
  285.     }
Now that we have now the PlayerController script, then let’s now do some several things:
  1. First attach the script to the Player Component.
  2. Set the Player position to X=18 and Y=13. tut41
  3. Add an Animator component in the Inspector.
  4. Add also an Audio Source component.
  5. Lastly, attach all the needed Components in the Inspector of PlayerController script. tut42
  6. Set the tag as Player.

Creating the Enemy Controller

We will now create the Enemy Controller to make the enemy chase the Player around the maze. To begin with firs go to Scripts folder then create a folder namely Enemy. Create now a Csharp script called EnemyController. Write these variables inside the EnemyController class to get started:
  1. [HideInInspector]
  2. public float moveSpeed = 5.9f;
  3. public enum Mode{
  4.         Chase,
  5.         Running,
  6.         Afraid,
  7.         Eaten
  8.     }
  9.  
  10. [HideInInspector]
  11. public float normalSpeed = 5.9f;
  12.  
  13. [HideInInspector]
  14. public float afraidSpeed = 2.9f;
  15.  
  16. [HideInInspector]
  17. public float eatenSpeed = 15f;
  18.  
  19. [HideInInspector]
  20. public int yellowRelease= 5;
  21.  
  22. [HideInInspector]
  23. public int purpleRelease = 15;
  24.  
  25. [HideInInspector]
  26. public int greenRelease = 20;
  27.  
  28. [HideInInspector]
  29. public float releaseTimer = 0;
  30.  
  31. [HideInInspector]
  32. public int afraidDuration = 10;
  33.  
  34. [HideInInspector]
  35. public int blinkingStartTime = 7;
  36.  
  37. public bool isInHouse = false;
  38. public bool canMove;
  39. public Intersect startingPosition;
  40. public Intersect runningHome;
  41. public Intersect house;
  42.  
  43. [HideInInspector]
  44. public int runningModeTimer1 = 7;
  45.  
  46.  
  47. [HideInInspector]
  48. public int chaseModeTimer1 = 20;
  49.  
  50. [HideInInspector]
  51. public int runningModeTimer2 = 7;
  52.  
  53. [HideInInspector]
  54. public int chaseModeTimer2 = 20;
  55.  
  56. [HideInInspector]
  57. public int runningModeTimer3 = 5;
  58.  
  59. [HideInInspector]
  60. public int chaseModeTimer3 = 20;
  61.  
  62. [HideInInspector]
  63. public int runningModeTimer4 = 5;
  64.  
  65. [HideInInspector]
  66. public int chaseModeTimer4 = 20;
  67.  
  68. public Sprite eyesUp;
  69. public Sprite eyesLeft;
  70. public Sprite eyesDown;
  71. public Sprite eyesRight;
  72. public RuntimeAnimatorController moveUp;
  73. public RuntimeAnimatorController moveDown;
  74. public RuntimeAnimatorController moveLeft;
  75. public RuntimeAnimatorController moveRight;
  76. public RuntimeAnimatorController pale;
  77. public RuntimeAnimatorController afraid;
  78.  
  79. public enum GhostType{
  80.         Red,
  81.         Yellow,
  82.         Purple,
  83.         Green
  84. }
  85.  
  86. public GhostType ghostType = GhostType.Red;
  87.  
  88. private Mode currentMode = Mode.Running;
  89. private Mode previousMode;
  90. private int changeModeCounter = 1;
  91. private float modeTimer = 0;
  92. private float afraidTimer = 0;
  93. private float blinkingTimer = 0;
  94. private bool afraidModeToPale = false;
  95. private GameObject player;
  96. private Intersect currentPosition, targetPosition, previousPosition;
  97. private Vector2 direction, nextDirection;
  98. private float previousSpeed;
Then write these blocks of code:
  1. // Use this for initialization
  2.     void Start () {
  3.         player = GameObject.FindGameObjectWithTag ("Player");
  4.         Intersect intersect = GetIntersectPosition (transform.localPosition);
  5.  
  6.         if(intersect != null){
  7.             currentPosition = intersect;
  8.         }
  9.  
  10.         if (isInHouse) {
  11.             direction = Vector2.up;
  12.             targetPosition = currentPosition.nearestIntersect [0];
  13.         } else {
  14.             direction = Vector2.left;
  15.             targetPosition = ChooseNextDirection ();
  16.         }
  17.    
  18.         previousPosition = currentPosition;
  19.  
  20.         UpdateAnimatorController ();
  21.     }
  22.  
  23.     public void Restart(){
  24.         canMove = true;
  25.         transform.GetComponent<SpriteRenderer> ().enabled = true;
  26.         transform.position = startingPosition.transform.position;
  27.         currentMode = Mode.Running;
  28.         releaseTimer = 0;
  29.         changeModeCounter = 1;
  30.         modeTimer = 0;
  31.         moveSpeed = normalSpeed;
  32.         previousSpeed = 0;
  33.  
  34.         if(transform.name != "Red Enemy"){
  35.             isInHouse = true;
  36.         }
  37.  
  38.         currentPosition = startingPosition;
  39.  
  40.         if (isInHouse) {
  41.             direction = Vector2.up;
  42.             targetPosition = currentPosition.nearestIntersect [0];
  43.         } else {
  44.             direction = Vector2.left;
  45.             targetPosition = ChooseNextDirection ();
  46.         }
  47.  
  48.         previousPosition = currentPosition;
  49.  
  50.         UpdateAnimatorController ();
  51.     }
  52.  
  53.     // Update is called once per frame
  54.     void Update () {
  55.         if(canMove){
  56.             ModeUpdate ();
  57.             Move ();
  58.             ReleaseEnemy ();
  59.             CheckCollission ();
  60.             CheckIsInHouse ();
  61.         }
  62.     }
  63.  
  64.     void CheckIsInHouse(){
  65.         if(currentMode == Mode.Eaten){
  66.             GameObject path = GetPathPosition (transform.position);
  67.  
  68.             if(path != null){
  69.                 if(path.transform.GetComponent<Intersect>() != null){
  70.                     if(path.transform.GetComponent<Intersect>().isHouse){
  71.                         moveSpeed = normalSpeed;
  72.                         Intersect intersect = GetIntersectPosition (transform.position);
  73.  
  74.                         if(intersect != null){
  75.                             currentPosition = intersect;
  76.                             direction = Vector2.up;
  77.                             targetPosition = currentPosition.nearestIntersect [0];
  78.                             previousPosition = currentPosition;
  79.                             currentMode = Mode.Chase;
  80.  
  81.                             UpdateAnimatorController ();
  82.                         }
  83.                     }
  84.                 }
  85.             }
  86.         }
  87.     }
  88.  
  89.     void CheckCollission(){
  90.         Rect enemyRect = new Rect (transform.position, transform.GetComponent<SpriteRenderer>().sprite.bounds.size / 4);
  91.         Rect playerRect = new Rect (player.transform.position, player.transform.GetComponent<SpriteRenderer>().sprite.bounds.size / 4);
  92.         if(enemyRect.Overlaps(playerRect)){
  93.             if (currentMode == Mode.Afraid) {
  94.                 Eaten ();
  95.             }else if(currentMode == Mode.Running || currentMode == Mode.Chase){
  96.                 GameplayController.instance.PlayerDied ();
  97.             }
  98.         }
  99.     }
  100.  
  101.     void Eaten(){
  102.         GameplayController.instance.counter++;
  103.  
  104.         GameController.instance.currentScore += GameplayController.instance.ScoreCounter (GameplayController.instance.counter);
  105.  
  106.         GameplayController.instance.StartConsumed (this.GetComponent<EnemyController> ());
  107.  
  108.         currentMode = Mode.Eaten;
  109.         previousSpeed = moveSpeed;
  110.         moveSpeed = eatenSpeed;
  111.         UpdateAnimatorController ();
  112.     }
  113.  
  114.  
  115.  
  116.     void UpdateAnimatorController(){
  117.         if (currentMode != Mode.Afraid && currentMode != Mode.Eaten) {
  118.             if (direction == Vector2.up) {
  119.                 transform.GetComponent<Animator> ().runtimeAnimatorController = moveUp;
  120.             } else if (direction == Vector2.down) {
  121.                 transform.GetComponent<Animator> ().runtimeAnimatorController = moveDown;
  122.             } else if (direction == Vector2.left) {
  123.                 transform.GetComponent<Animator> ().runtimeAnimatorController = moveLeft;
  124.             } else if (direction == Vector2.right) {
  125.                 transform.GetComponent<Animator> ().runtimeAnimatorController = moveRight;
  126.             } else {
  127.                 transform.GetComponent<Animator> ().runtimeAnimatorController = moveLeft;
  128.             }
  129.         }
  130.         else if (currentMode == Mode.Afraid) {
  131.             transform.GetComponent<Animator> ().runtimeAnimatorController = afraid;
  132.         }else if (currentMode == Mode.Eaten) {
  133.             transform.GetComponent<Animator> ().runtimeAnimatorController = null;
  134.             if (direction == Vector2.up) {
  135.                 transform.GetComponent<SpriteRenderer> ().sprite = eyesUp;
  136.             } else if (direction == Vector2.down) {
  137.                 transform.GetComponent<SpriteRenderer> ().sprite = eyesDown;
  138.             } else if (direction == Vector2.left) {
  139.                 transform.GetComponent<SpriteRenderer> ().sprite = eyesLeft;
  140.             } else if (direction == Vector2.right) {
  141.                 transform.GetComponent<SpriteRenderer> ().sprite = eyesRight;
  142.             }
  143.         }
  144.     }
  145.  
  146.     void Move(){
  147.         if(targetPosition != currentPosition && targetPosition != null && !isInHouse){
  148.             if (CheckDetection()) {
  149.  
  150.                 currentPosition = targetPosition;
  151.                 transform.localPosition = currentPosition.transform.position;
  152.                 GameObject otherTeleporter = GetTeleporter (currentPosition.transform.position);
  153.  
  154.                 if (otherTeleporter != null) {
  155.                     transform.localPosition = otherTeleporter.transform.position;
  156.                     currentPosition = otherTeleporter.GetComponent<Intersect> ();
  157.                 }
  158.  
  159.                 targetPosition = ChooseNextDirection ();
  160.                 previousPosition = currentPosition;
  161.                 currentPosition = null;
  162.  
  163.                 UpdateAnimatorController ();
  164.  
  165.             } else {
  166.                 transform.localPosition += (Vector3)direction * moveSpeed * Time.deltaTime;
  167.             }
  168.         }
  169.     }
  170.  
  171.     void ModeUpdate(){
  172.         if (currentMode != Mode.Afraid) {
  173.             modeTimer += Time.deltaTime;
  174.  
  175.             if (changeModeCounter == 1) {
  176.                 if (currentMode == Mode.Running && modeTimer > runningModeTimer1) {
  177.                     ChangeMode (Mode.Chase);
  178.                     modeTimer = 0;
  179.                 }
  180.  
  181.                 if (currentMode == Mode.Chase && modeTimer > chaseModeTimer1) {
  182.                     changeModeCounter = 2;
  183.                     ChangeMode (Mode.Running);
  184.                     modeTimer = 0;
  185.                 }
  186.             } else if (changeModeCounter == 2) {
  187.                 if(currentMode == Mode.Running && modeTimer > runningModeTimer2){
  188.                     ChangeMode (Mode.Chase);
  189.                     modeTimer = 0;
  190.                 }
  191.  
  192.                 if(currentMode == Mode.Chase && modeTimer > chaseModeTimer2){
  193.                     changeModeCounter = 3;
  194.                     ChangeMode (Mode.Running);
  195.                     modeTimer = 0;
  196.                 }
  197.  
  198.             } else if (changeModeCounter == 3) {
  199.                 if(currentMode == Mode.Running && modeTimer > runningModeTimer3){
  200.                     ChangeMode (Mode.Chase);
  201.                     modeTimer = 0;
  202.                 }
  203.  
  204.                 if(currentMode == Mode.Chase && modeTimer > chaseModeTimer3){
  205.                     changeModeCounter = 4;
  206.                     ChangeMode (Mode.Running);
  207.                     modeTimer = 0;
  208.                 }
  209.             } else if (changeModeCounter == 4) {
  210.                 if(currentMode == Mode.Running && modeTimer > runningModeTimer4){
  211.                     ChangeMode (Mode.Chase);
  212.                     modeTimer = 0;
  213.                 }
  214.             }
  215.         } else if(currentMode == Mode.Afraid){
  216.             afraidTimer += Time.deltaTime;
  217.             if(afraidTimer >= afraidDuration){
  218.                 afraidTimer = 0;
  219.                 ChangeMode (previousMode);
  220.                 if (MusicController.instance != null && GameController.instance != null) {
  221.                     if (GameController.instance.isMusicOn) {
  222.                         MusicController.instance.PlayGameplaySound ();
  223.                     }
  224.                 }
  225.             }
  226.  
  227.             if(afraidTimer >= blinkingStartTime){
  228.                 blinkingTimer += Time.deltaTime;
  229.                 if(blinkingTimer >= 0.1f){
  230.                     blinkingTimer = 0;
  231.                     if (afraidModeToPale) {
  232.                         transform.GetComponent<Animator> ().runtimeAnimatorController = afraid;
  233.                         afraidModeToPale = false;
  234.                     } else {
  235.                         transform.GetComponent<Animator> ().runtimeAnimatorController = pale;
  236.                         afraidModeToPale = true;
  237.                     }
  238.                 }
  239.             }
  240.         }
  241.     }
  242.  
  243.     void ChangeMode(Mode m){
  244.        
  245.         if(currentMode == Mode.Afraid){
  246.             moveSpeed = previousSpeed;
  247.         }
  248.  
  249.         if(m == Mode.Afraid){
  250.             previousSpeed = moveSpeed;
  251.             moveSpeed = afraidSpeed;
  252.         }
  253.        
  254.         if(currentMode != m){
  255.             previousMode = currentMode;
  256.             currentMode = m;
  257.         }
  258.  
  259.        
  260.  
  261.  
  262.         UpdateAnimatorController ();
  263.     }
  264.  
  265.     public void StartAfraidMode(){
  266.         if(currentMode != Mode.Eaten){
  267.             afraidTimer = 0;
  268.             GameplayController.instance.counter = 0;
  269.             ChangeMode (Mode.Afraid);
  270.         }
  271.         if (GameController.instance != null && MusicController.instance != null) {
  272.             if (GameController.instance.isMusicOn) {
  273.                 MusicController.instance.PlayCoinRush ();
  274.             }
  275.         }
  276.     }
  277.  
  278.     Vector2 GetRedTargetPos(){
  279.         Vector2 playerPosition = player.transform.localPosition;
  280.         Vector2 targetPath = new Vector2 (Mathf.RoundToInt (playerPosition.x), Mathf.RoundToInt (playerPosition.y));
  281.  
  282.         return targetPath;
  283.     }
  284.  
  285.     Vector2 GetYellowTargetPos(){
  286.    
  287.         Vector2 playerPosition = player.transform.localPosition;
  288.         Vector2 playerOrientation = player.GetComponent<PlayerController> ().position;
  289.         int playerPositionX = Mathf.RoundToInt (playerPosition.x);
  290.         int playerPositionY = Mathf.RoundToInt (playerPosition.y);
  291.  
  292.         Vector2 playerPath = new Vector2 (playerPositionX, playerPositionY);
  293.         Vector2 targetPath = playerPath + (4 * playerOrientation);
  294.  
  295.         return targetPath;
  296.  
  297.     }
  298.  
  299.     Vector2 GetPurpleTargetPos(){
  300.         Vector2 playerPosition = player.transform.localPosition;
  301.         Vector2 playerOrientation = player.GetComponent<PlayerController> ().position;
  302.         int playerPositionX = Mathf.RoundToInt (playerPosition.x);
  303.         int playerPositionY = Mathf.RoundToInt (playerPosition.y);
  304.  
  305.         Vector2 playerPath = new Vector2 (playerPositionX, playerPositionY);
  306.         Vector2 targetPath = playerPath + (2 * playerOrientation);
  307.  
  308.  
  309.         Vector2 tempPosition = GameObject.Find ("Red Enemy").transform.localPosition;
  310.         int PurplePositionX = Mathf.RoundToInt (tempPosition.x);
  311.         int PurplePositionY = Mathf.RoundToInt (tempPosition.y);
  312.  
  313.         tempPosition = new Vector2 (PurplePositionX, PurplePositionY);
  314.         float distance = GetDistance (tempPosition, targetPath);
  315.         distance *= 2;
  316.         targetPath = new Vector2 (tempPosition.x + distance, tempPosition.y + distance);
  317.         return targetPath;
  318.     }
  319.  
  320.     Vector2 GetGreenTargetPos(){
  321.         Vector2 playerPosition = player.transform.localPosition;
  322.         float distance = GetDistance (transform.localPosition, playerPosition);
  323.         Vector2 targetPath = Vector2.zero;
  324.  
  325.         if(distance >= 8){
  326.             targetPath = new Vector2 (Mathf.RoundToInt (playerPosition.x), Mathf.RoundToInt (playerPosition.y));
  327.  
  328.         }else if(distance <= 8){
  329.             targetPath = runningHome.transform.position;
  330.         }
  331.  
  332.         return targetPath;
  333.     }
  334.  
  335.     Vector2 GetTargetPath(){
  336.         Vector2 targetPath = Vector2.zero;
  337.         if(ghostType == GhostType.Red){
  338.             targetPath = GetRedTargetPos ();
  339.         }else if(ghostType == GhostType.Yellow){
  340.             targetPath = GetYellowTargetPos ();
  341.         }else if(ghostType == GhostType.Purple){
  342.             targetPath = GetPurpleTargetPos ();
  343.         }else if(ghostType == GhostType.Green){
  344.             targetPath = GetGreenTargetPos ();
  345.         }
  346.  
  347.         return targetPath;
  348.     }
  349.  
  350.     Vector2 GetRandomPath(){
  351.         int x = Random.Range (0, 28);
  352.         int y = Random.Range (0, 36);
  353.  
  354.         return new Vector2 (x, y);
  355.     }
  356.  
  357.     void ReleaseYellow(){
  358.         if(ghostType == GhostType.Yellow && isInHouse){
  359.             isInHouse = false;
  360.         }
  361.     }
  362.  
  363.     void ReleasePurple(){
  364.         if(ghostType == GhostType.Purple && isInHouse){
  365.             isInHouse = false;
  366.         }
  367.     }
  368.  
  369.     void ReleaseGreen(){
  370.         if(ghostType == GhostType.Green && isInHouse){
  371.             isInHouse = false;
  372.         }
  373.     }
  374.  
  375.     void ReleaseEnemy(){
  376.         releaseTimer += Time.deltaTime;
  377.         if(releaseTimer > yellowRelease){
  378.             ReleaseYellow ();
  379.         }
  380.  
  381.         if(releaseTimer > purpleRelease){
  382.             ReleasePurple ();
  383.         }
  384.  
  385.         if(releaseTimer > greenRelease){
  386.             ReleaseGreen ();
  387.         }
  388.  
  389.     }
  390.  
  391.     private Intersect ChooseNextDirection(){
  392.         Vector2 targetPath = Vector2.zero;
  393.         if(currentMode == Mode.Chase){
  394.             targetPath = GetTargetPath ();
  395.         }else if(currentMode == Mode.Running){
  396.             targetPath = runningHome.transform.position;
  397.         }else if(currentMode == Mode.Afraid){
  398.             targetPath = GetRandomPath ();
  399.         }else if(currentMode == Mode.Eaten){
  400.             targetPath = house.transform.position;
  401.         }
  402.         Intersect moveToIntersect = null;
  403.         Intersect[] foundIntersection = new Intersect[4];
  404.         Vector2[] foundIntersectDirection = new Vector2[4];
  405.         int intersectCounter = 0;
  406.         for(int i = 0; i < currentPosition.nearestIntersect.Length; i++){
  407.             if(currentPosition.possibleDirection[i] != direction *-1){
  408.                 if (currentMode != Mode.Eaten) {
  409.                     GameObject path = GetPathPosition (currentPosition.transform.position);
  410.                     if (path.transform.GetComponent<Intersect> ().isHouseEntrance == true) {
  411.                         if (currentPosition.possibleDirection [i] != Vector2.down) {
  412.                             foundIntersection [intersectCounter] = currentPosition.nearestIntersect [i];
  413.                             foundIntersectDirection [intersectCounter] = currentPosition.possibleDirection [i];
  414.                             intersectCounter++;
  415.                         }
  416.                     } else {
  417.                         foundIntersection [intersectCounter] = currentPosition.nearestIntersect [i];
  418.                         foundIntersectDirection [intersectCounter] = currentPosition.possibleDirection [i];
  419.                         intersectCounter++;
  420.                     }
  421.                 } else {
  422.                     foundIntersection [intersectCounter] = currentPosition.nearestIntersect [i];
  423.                     foundIntersectDirection [intersectCounter] = currentPosition.possibleDirection [i];
  424.                     intersectCounter++;
  425.                 }
  426.             }
  427.         }
  428.  
  429.         if(foundIntersection.Length == 1){
  430.             moveToIntersect = foundIntersection [0];
  431.             direction = foundIntersectDirection [0];
  432.         }
  433.  
  434.         if(foundIntersection.Length > 1){
  435.             float leastDistance = 100000f;
  436.             for (int i = 0; i < foundIntersection.Length; i++) {
  437.                 if(foundIntersectDirection[i] != Vector2.zero){
  438.                     float distance = GetDistance (foundIntersection [i].transform.position, targetPath);
  439.                     if(distance < leastDistance){
  440.                         leastDistance = distance;
  441.                         moveToIntersect = foundIntersection [i];
  442.                         direction = foundIntersectDirection [i];
  443.                     }
  444.                 }
  445.             }
  446.         }
  447.  
  448.         return moveToIntersect;
  449.     }
  450.  
  451.     private Intersect GetIntersectPosition(Vector2 position){
  452.         GameObject path = GameplayController.instance.gameSize [(int)position.x, (int)position.y];
  453.         if(path != null){
  454.             if(path.GetComponent<Intersect>() != null){
  455.                 return path.GetComponent<Intersect> ();
  456.             }
  457.         }
  458.  
  459.         return null;
  460.     }
  461.  
  462.     private GameObject GetPathPosition(Vector2 position){
  463.         int pathX = Mathf.RoundToInt (position.x);
  464.         int pathY = Mathf.RoundToInt (position.y);
  465.         GameObject path = GameplayController.instance.gameSize [pathX, pathY];
  466.  
  467.         if(path != null){
  468.             return path;
  469.         }
  470.  
  471.         return null;
  472.     }
  473.  
  474.     private GameObject GetTeleporter(Vector2 pos){
  475.         GameObject path = GameplayController.instance.gameSize [(int)pos.x, (int)pos.y];
  476.         if(path != null){
  477.             if(path.GetComponent<Intersect>().isTeleporter){
  478.                 GameObject otherTeleporter = path.GetComponent<Intersect> ().gateWay;
  479.                 return otherTeleporter;
  480.             }
  481.         }
  482.         return null;
  483.     }
  484.  
  485.     private float LengthFromIntersect(Vector2 targetPosition){
  486.         Vector2 temp = targetPosition - (Vector2)previousPosition.transform.position;
  487.         return temp.sqrMagnitude;
  488.     }
  489.  
  490.     private bool CheckDetection(){
  491.         float intersectToTarget = LengthFromIntersect (targetPosition.transform.position);
  492.         float intersectToCurrent = LengthFromIntersect (transform.localPosition);
  493.  
  494.         return intersectToCurrent > intersectToTarget;
  495.     }
  496.  
  497.  
  498.  
  499.     private float GetDistance(Vector2 dist1, Vector2 dist2){
  500.         float x = dist1.x - dist2.x;
  501.         float y = dist1.y - dist2.y;
  502.  
  503.         float distance = Mathf.Sqrt (x * x + y * y);
  504.  
  505.         return distance;
  506.     }
Now that we have now the EnemyController script, there are still things that we need to do first:
  1. First attach the script to each Enemy components; Red Enemy, Yellow Enemy, Purple Enemy and Green Enemy.
  2. Set each Enemies Transform and Tag them as Enemy shown in the image below. tut43
  3. Add an Animator to each enemy component.
  4. Drag and assign each corresponding component to EnemyController script inspector. tut44

Creating the Gameplay Controller

Now we will create the Gameplay Controller. This will be the game mechanics of the game. It will handle the flow of the game to make be playable. Create a GameObject then name it as Gameplay Controller. Then create a script and save it to Game Controllers folder as GameplayController. Write these important variables to make the game work properly:
  1. public static GameplayController instance;
  2.  
  3. public GameObject[,] gameSize = new GameObject[width, height];
  4. public GameObject pausePanel;
  5. public int totalCoins;
  6. public int score;
  7. public int highScore;
  8. public int maxLive;
  9. public Text readyText;
  10. public Text highscoreText;
  11. public Text enemyScoreText;
  12. public Text scoreText;
  13. public Text blinkingScore;
  14. public Image[] liveSprites;
  15. public int coins;
  16.  
  17. [HideInInspector]
  18. public int scoreCounter;
  19.  
  20. [HideInInspector]
  21. public int counter;
  22.  
  23. private bool gameInProgress, gameInPause;
  24. private bool isDied;
  25. private bool isStartEat;
  26. private bool newHighscore;
  27. private static int width = 28;
  28. private static int height = 36;
  29. private int lives;
Note: Make sure to import these important modules:
  1. using UnityEngine.UI;
  2. using UnityEngine.SceneManagement;
Then write the rest of the codes:
  1. void Awake(){
  2.         CreateInstance ();
  3.     }
  4.  
  5.     // Use this for initialization
  6.     void Start () {
  7.         InitializeGameplayVariables ();
  8.  
  9.         StartGame ();
  10.     }
  11.    
  12.     // Update is called once per frame
  13.     void Update () {
  14.         UpdateGameplay ();
  15.     }
  16.  
  17.     void UpdateGameplay(){
  18.         if(GameController.instance != null){
  19.             score = GameController.instance.currentScore;
  20.             scoreText.text = score.ToString("N0");
  21.             if(GameController.instance.currentScore >= GameController.instance.highScore){
  22.                 GameController.instance.highScore = score;
  23.                 highScore = GameController.instance.highScore;
  24.                 highscoreText.text = highScore.ToString ("N0");
  25.                 GameController.instance.Save ();
  26.             }
  27.         }
  28.  
  29.         CheckCoins ();
  30.     }
  31.  
  32.     void CreateInstance(){
  33.         if(instance == null){
  34.             instance = this;
  35.         }
  36.     }
  37.        
  38.     void InitializeGameplayVariables(){
  39.         InitializeGameSize ();
  40.  
  41.         if(GameController.instance != null){
  42.             if (GameController.instance.isGameStartedInMainMenu) {
  43.                 lives = maxLive - 1;
  44.                 GameController.instance.currentLives = lives;
  45.                 GameController.instance.currentScore = 0;
  46.  
  47.                 score = GameController.instance.currentScore;
  48.                 highScore = GameController.instance.highScore;
  49.  
  50.                 scoreText.text = score.ToString ("N0");
  51.                 highscoreText.text = highScore.ToString ("N0");
  52.                 GameController.instance.isGameStartedInMainMenu = false;
  53.  
  54.             }else {
  55.                 lives = GameController.instance.currentLives;
  56.                 score = GameController.instance.currentScore;
  57.                 highScore = GameController.instance.highScore;
  58.                 scoreText.text = score.ToString ("N0");
  59.                 highscoreText.text = highScore.ToString ("N0");
  60.             }
  61.         }
  62.            
  63.         for(int i = 0; i < maxLive; i++){
  64.             if (lives > i) {
  65.                 liveSprites [i].gameObject.SetActive (true);
  66.             } else {
  67.                 liveSprites [i].gameObject.SetActive (false);
  68.             }
  69.         }
  70.  
  71.     }
  72.  
  73.     void CheckCoins(){
  74.         if(totalCoins == coins){
  75.             LevelComplete ();
  76.         }
  77.     }
  78.  
  79.     void LevelComplete(){
  80.  
  81.         StartCoroutine (CompleteTimer (2));
  82.     }
  83.  
  84.     IEnumerator CompleteTimer(float delay){
  85.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  86.         player.transform.GetComponent<PlayerController> ().canMove = false;
  87.         player.transform.GetComponent<Animator> ().enabled = false;
  88.  
  89.         if(GameController.instance != null && MusicController.instance != null){
  90.             if(GameController.instance.isMusicOn){
  91.                 MusicController.instance.StopAllSounds ();
  92.             }
  93.         }
  94.  
  95.         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  96.  
  97.         foreach(GameObject enemy in enemies){
  98.             enemy.transform.GetComponent<EnemyController> ().canMove = false;
  99.             enemy.transform.GetComponent<Animator> ().enabled = false;
  100.         }
  101.  
  102.         yield return new WaitForSeconds (delay);
  103.  
  104.         StartCoroutine (PrepareNextLevel (2));
  105.     }
  106.  
  107.     IEnumerator PrepareNextLevel(float delay){
  108.         if(GameController.instance != null){
  109.             GameController.instance.currentLevel++;
  110.         }
  111.  
  112.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  113.         player.transform.GetComponent<SpriteRenderer> ().enabled = false;
  114.         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  115.         foreach(GameObject enemy in enemies){
  116.             enemy.transform.GetComponent<SpriteRenderer> ().enabled = false;
  117.         }
  118.            
  119.         yield return new WaitForSeconds (delay);
  120.         StartNextLevel ();
  121.     }
  122.  
  123.     void StartNextLevel(){
  124.         if (SceneManager.GetActiveScene ().buildIndex == SceneManager.sceneCountInBuildSettings - 1) {
  125.             StartCoroutine (FinishAllLevel (5));
  126.         } else {
  127.             if(GameController.instance != null){
  128.                 SceneManager.LoadScene ("Level " + GameController.instance.currentLevel);
  129.             }
  130.  
  131.         }
  132.     }
  133.  
  134.     IEnumerator FinishAllLevel(float delay){
  135.         readyText.text = "LEVEL COMPLETED";
  136.         readyText.color = Color.blue;
  137.         readyText.gameObject.SetActive (true);
  138.  
  139.         yield return new WaitForSeconds (delay);
  140.  
  141.         SceneManager.LoadScene ("Main Menu");
  142.     }
  143.  
  144.     void InitializeGameSize(){
  145.         Object[] obj = GameObject.FindObjectsOfType (typeof(GameObject));
  146.  
  147.         foreach(GameObject newObj in obj){
  148.             Vector2 position = newObj.transform.position;
  149.             if (newObj.name != "Player" && newObj.name != "Non Intersect" && newObj.name != "Intersect" && newObj.name != "Maze" && !newObj.CompareTag("Enemy") && !newObj.CompareTag("Running Point") && !newObj.CompareTag("Gameplay UI")) {
  150.                 if(newObj.GetComponent<Coins>() != null){
  151.                     if(newObj.GetComponent<Coins>().silverCoin || newObj.GetComponent<Coins>().goldCoin ){
  152.                         totalCoins++;
  153.                     }
  154.                 }
  155.                 gameSize [(int)position.x, (int)position.y] = newObj;
  156.             }
  157.         }
  158.     }
  159.  
  160.     public void StartConsumed(EnemyController consumed){
  161.         if(!isStartEat){
  162.  
  163.             StopAllCoroutines ();
  164.  
  165.             isStartEat = true;
  166.  
  167.             GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  168.             foreach(GameObject enemy in enemies){
  169.                 enemy.transform.GetComponent<EnemyController> ().canMove = false;
  170.             }
  171.  
  172.             GameObject player = GameObject.FindGameObjectWithTag ("Player");
  173.             player.transform.GetComponent<PlayerController> ().canMove = false;
  174.             player.transform.GetComponent<SpriteRenderer> ().enabled = false;
  175.  
  176.             consumed.transform.GetComponent<SpriteRenderer> ().enabled = false;
  177.  
  178.             if(GameController.instance != null && MusicController.instance != null){
  179.                 if(GameController.instance.isMusicOn){
  180.                     MusicController.instance.audioSource.Stop ();
  181.                 }
  182.             }
  183.  
  184.             Vector2 position = consumed.transform.position;
  185.             Vector2 viewPortPoint = Camera.main.WorldToViewportPoint (position);
  186.             enemyScoreText.GetComponent<RectTransform> ().anchorMin = viewPortPoint;
  187.             enemyScoreText.GetComponent<RectTransform> ().anchorMax = viewPortPoint;
  188.             enemyScoreText.text = ScoreCounter (counter).ToString ();
  189.             enemyScoreText.gameObject.SetActive (true);
  190.  
  191.             if(GameController.instance != null){
  192.                 if(GameController.instance.isMusicOn){
  193.                     player.transform.GetComponent<PlayerController> ().GetBite ();
  194.                 }
  195.  
  196.             }
  197.  
  198.             StartCoroutine (ProcessConsumed (0.75f, consumed));
  199.  
  200.         }
  201.     }
  202.  
  203.     public int ScoreCounter(int counter){
  204.         switch(counter){
  205.         case 1:
  206.             scoreCounter = 200;
  207.             break;
  208.  
  209.         case 2:
  210.             scoreCounter = 400;
  211.             break;
  212.  
  213.         case 3:
  214.             scoreCounter = 800;
  215.             break;
  216.  
  217.         case 4:
  218.             scoreCounter = 1600;
  219.             break;
  220.         }
  221.  
  222.         return scoreCounter;
  223.     }
  224.  
  225.     IEnumerator StartBlinking(Text blinkingText){
  226.         yield return new WaitForSeconds (0.25f);
  227.  
  228.         blinkingText.GetComponent<Text>().enabled = !blinkingText.GetComponent<Text>().enabled;
  229.         StartCoroutine (StartBlinking (blinkingText));
  230.     }
  231.  
  232.     IEnumerator ProcessConsumed(float delay, EnemyController consumed){
  233.         yield return new WaitForSeconds (delay);
  234.  
  235.         enemyScoreText.gameObject.SetActive (false);
  236.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  237.         player.transform.GetComponent<SpriteRenderer> ().enabled = true;
  238.  
  239.         consumed.transform.GetComponent<SpriteRenderer> ().enabled = true;
  240.  
  241.         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  242.         foreach(GameObject enemy in enemies){
  243.             enemy.transform.GetComponent<EnemyController> ().canMove = true;
  244.         }
  245.  
  246.         player.transform.GetComponent<PlayerController> ().canMove = true;
  247.  
  248.         if(GameController.instance != null && MusicController.instance != null){
  249.             if(GameController.instance.isMusicOn){
  250.                 MusicController.instance.audioSource.Play ();
  251.             }
  252.         }
  253.  
  254.         isStartEat = false;
  255.         StartCoroutine (StartBlinking (blinkingScore));
  256.     }
  257.  
  258.     public void StartGame(){
  259.         readyText.gameObject.SetActive (true);
  260.  
  261.         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  262.         foreach(GameObject enemy in enemies){
  263.             enemy.transform.GetComponent<SpriteRenderer> ().enabled = false;
  264.             enemy.transform.GetComponent<EnemyController>().canMove = false;
  265.         }
  266.  
  267.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  268.         player.transform.GetComponent<Animator> ().enabled = false;
  269.         player.transform.GetComponent<PlayerController> ().canMove = false;
  270.  
  271.         if(GameController.instance != null && MusicController.instance != null){
  272.             if(GameController.instance.isMusicOn){
  273.                 MusicController.instance.PlayStartSound ();
  274.             }else {
  275.                 MusicController.instance.StopAllSounds ();
  276.             }
  277.         }
  278.  
  279.         StartCoroutine (StartGameTimer (3.5f));
  280.         StartCoroutine (StartBlinking (blinkingScore));
  281.     }
  282.  
  283.     private void RestartGame(){
  284.  
  285.         readyText.gameObject.SetActive (true);
  286.  
  287.         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  288.         foreach(GameObject enemy in enemies){
  289.             enemy.transform.GetComponent<SpriteRenderer> ().enabled = false;
  290.             enemy.transform.GetComponent<EnemyController>().canMove = false;
  291.         }
  292.  
  293.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  294.         player.transform.GetComponent<Animator> ().enabled = false;
  295.         player.transform.GetComponent<SpriteRenderer> ().sprite = player.transform.GetComponent<PlayerController> ().standby;
  296.         player.transform.GetComponent<PlayerController> ().canMove = false;
  297.  
  298.  
  299.  
  300.         StartCoroutine (RestartGameTimer (1));
  301.            
  302.  
  303.     }
  304.  
  305.     IEnumerator RestartGameTimer(float delay){
  306.         yield return new WaitForSeconds (delay);
  307.  
  308.         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  309.         foreach(GameObject enemy in enemies){
  310.             enemy.transform.GetComponent<SpriteRenderer> ().enabled = true;
  311.             enemy.transform.GetComponent<EnemyController> ().canMove = true;
  312.         }
  313.  
  314.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  315.         player.transform.GetComponent<Animator> ().enabled = true;
  316.         player.transform.GetComponent<PlayerController> ().canMove = true;
  317.  
  318.         readyText.gameObject.SetActive (false);
  319.  
  320.         if(GameController.instance != null && MusicController.instance != null){
  321.             if(GameController.instance.isMusicOn){
  322.                 MusicController.instance.PlayGameplaySound ();
  323.             }
  324.         }
  325.  
  326.     }
  327.  
  328.  
  329.     IEnumerator StartGameTimer(float delay){
  330.         yield return new WaitForSeconds (delay);
  331.  
  332.         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  333.         foreach(GameObject enemy in enemies){
  334.             enemy.transform.GetComponent<SpriteRenderer> ().enabled = true;
  335.             enemy.transform.GetComponent<EnemyController> ().canMove = true;
  336.         }
  337.  
  338.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  339.         player.transform.GetComponent<Animator> ().enabled = true;
  340.         player.transform.GetComponent<PlayerController> ().canMove = true;
  341.  
  342.         readyText.gameObject.SetActive (false);
  343.  
  344.         if (MusicController.instance != null && GameController.instance != null) {
  345.             if (GameController.instance.isMusicOn) {
  346.                 MusicController.instance.PlayGameplaySound ();
  347.             }
  348.         }
  349.            
  350.         gameInProgress = true;
  351.     }
  352.        
  353.     public void PlayerDied(){
  354.         if(!isDied){
  355.             isDied = true;
  356.        
  357.             GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  358.  
  359.             foreach(GameObject enemy in enemies){
  360.                 enemy.transform.GetComponent<EnemyController> ().canMove = false;
  361.             }
  362.  
  363.             GameObject player = GameObject.FindGameObjectWithTag ("Player");
  364.             player.transform.GetComponent<Animator> ().enabled = false;
  365.             player.transform.GetComponent<PlayerController> ().canMove = false;
  366.             if(MusicController.instance != null && GameController.instance != null){
  367.                 if (GameController.instance.isMusicOn) {    
  368.                     MusicController.instance.StopAllSounds ();
  369.                 }
  370.             }
  371.             StartCoroutine (PlayerDiedTimer(2));
  372.         }
  373.     }
  374.  
  375.     IEnumerator PlayerDiedTimer(float delay){
  376.         yield return new WaitForSeconds (delay);
  377.         GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  378.  
  379.         foreach(GameObject enemy in enemies){
  380.             enemy.transform.GetComponent<SpriteRenderer> ().enabled = false;
  381.         }
  382.  
  383.         StartCoroutine (DeathAnimation (1.9f));
  384.     }
  385.  
  386.     IEnumerator DeathAnimation(float delay){
  387.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  388.  
  389.         player.transform.GetComponent<Animator>().runtimeAnimatorController = player.transform.GetComponent<PlayerController>().deathAnimation;
  390.         player.transform.GetComponent<Animator> ().enabled = true;
  391.  
  392.         if(GameController.instance != null && MusicController.instance != null){
  393.             if(GameController.instance.isMusicOn){
  394.                 MusicController.instance.PlayDeathSound ();
  395.             }
  396.         }
  397.  
  398.         yield return new WaitForSeconds (delay);
  399.  
  400.         StartCoroutine (Restarting (2));
  401.     }
  402.  
  403.     IEnumerator Restarting(float delay){
  404.         GameObject player = GameObject.FindGameObjectWithTag ("Player");
  405.         player.transform.GetComponent<SpriteRenderer> ().enabled = false;
  406.         yield return new WaitForSeconds (delay);
  407.  
  408.         RestartLevel ();
  409.     }
  410.  
  411.     public void RestartLevel(){
  412.  
  413.         lives -= 1;
  414.  
  415.         if (lives < 0) {
  416.             readyText.text = "GAME OVER";
  417.             readyText.color = Color.red;
  418.             readyText.gameObject.SetActive (true);
  419.             StartCoroutine (BackToMainMenu (3f));
  420.  
  421.         } else {
  422.             GameObject player = GameObject.FindGameObjectWithTag ("Player");
  423.             player.transform.GetComponent<PlayerController> ().Restart ();
  424.             player.transform.localRotation = Quaternion.Euler (0, 0, 0);
  425.             player.transform.localScale = new Vector3 (1, 1, 1);
  426.             GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  427.  
  428.             foreach(GameObject enemy in enemies){
  429.                 enemy.transform.GetComponent<EnemyController> ().Restart();
  430.             }
  431.  
  432.             isDied = false;
  433.             RestartGame ();
  434.  
  435.         }
  436.  
  437.         for(int i = 0; i < maxLive; i++){
  438.             if (lives > i) {
  439.                 liveSprites [i].gameObject.SetActive (true);
  440.             } else {
  441.                 liveSprites [i].gameObject.SetActive (false);
  442.             }
  443.         }
  444.     }
  445.  
  446.     IEnumerator BackToMainMenu(float delay){
  447.         yield return new WaitForSeconds (delay);
  448.         SceneManager.LoadScene ("Main Menu");
  449.     }
  450.  
  451.     public void PauseButton(){
  452.         if(!gameInPause){
  453.             if(gameInProgress){
  454.                 gameInPause = true;
  455.                 gameInProgress = false;
  456.                 GameObject player = GameObject.FindGameObjectWithTag ("Player");
  457.                 player.transform.GetComponent<PlayerController> ().canMove = false;
  458.                 GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  459.  
  460.                 foreach(GameObject enemy in enemies){
  461.                     enemy.transform.GetComponent<EnemyController> ().canMove = false;
  462.                 }
  463.  
  464.                 pausePanel.SetActive (true);
  465.             }
  466.         }
  467.     }
  468.  
  469.     public void ResumeButton(){
  470.         if(gameInPause){
  471.             if(!gameInProgress){
  472.                 gameInPause = false;
  473.                 gameInProgress = true;
  474.                 GameObject player = GameObject.FindGameObjectWithTag ("Player");
  475.                 player.transform.GetComponent<PlayerController> ().canMove = true;
  476.                 GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
  477.  
  478.                 foreach(GameObject enemy in enemies){
  479.                     enemy.transform.GetComponent<EnemyController> ().canMove = true;
  480.                 }
  481.  
  482.                 pausePanel.SetActive (false);
  483.             }
  484.         }
  485.     }
  486.  
  487.     public void QuitButton(){
  488.        
  489.         SceneManager.LoadScene ("Main Menu");
  490.     }
After creating the script attach it to the Gameplay Controller component. And then attach all the needed components in the Inspector of GameplayController script. tut45 Note: Make sure to attach the Script to each Buttons Runtime script. tut46

Building the Game and Script Execution Order

Script Execution Order

Now we’re done with everything there is still on left to do. First go to the Edit click Project Settings, then Script Execution Order. Set the values as show below in the image. tut49

Building the Game

To build the game go to the file menu, then choose Build Setting. Drag all the scenes in the empty box and set the platform to android as shown below. tut47 After you're done click the Player Setting, then fill up the required information in order to build the application. tut48 Click Build to build the game into an Android application. There you have it we successfully created a Simple Retro Arcade Game. I hope that this tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Tags

my name is isaac, i have lots of paid projects on android piling up, please will like us to work together, here is my email, [email protected] or mobile number : +2347066239250

Add new comment