Coin Run - A Simple Retro Arcade Game For Android/IOS
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. 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. This is how the Unity Game Engine Environment looks like. 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".Changing the Platform
Under the File, Click Build Setting and select Android, and then click Switch Platform.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"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. Before working on the GameObject make sure to reset its transform to avoid conflict in the future. 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. 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.- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class GameController : MonoBehaviour {
- // Use this for initialization
- void Start () {
- }
- // Update is called once per frame
- void Update () {
- }
- }
- using System;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- Then write these blocks of code inside the GameController class.
- public static GameController instance;
- public bool isGameStartedFirstTime;
- public bool isMusicOn;
- public bool isGameStartedInMainMenu;
- public int highScore;
- public int currentScore;
- public int currentLives;
- public int currentLevel = 1;
- private GameData data;
- void Awake(){
- MakeInstance ();
- InitializeGameVariables ();
- }
- // Use this for initialization
- void Start () {
- }
- // Update is called once per frame
- void Update () {
- }
- void MakeInstance(){
- if (instance != null) {
- Destroy (gameObject);
- } else {
- instance = this;
- DontDestroyOnLoad (gameObject);
- }
- }
- void InitializeGameVariables(){
- Load ();
- if (data != null) {
- isGameStartedFirstTime = data.GetIsGameStartedFirstTime ();
- } else {
- isGameStartedFirstTime = true;
- }
- if (isGameStartedFirstTime) {
- isMusicOn = true;
- highScore = 500;
- isGameStartedFirstTime = false;
- data.SetIsGameStartedFirstTIme (isGameStartedFirstTime);
- data.SetHighScore (highScore);
- data.SetIsMusicOn (isMusicOn);
- Save ();
- Load ();
- } else {
- isMusicOn = data.GetIsMusicOn();
- highScore = data.GetHighScore ();
- isGameStartedFirstTime = data.GetIsGameStartedFirstTime ();
- }
- }
- public void Save(){
- FileStream file = null;
- try{
- file = File.Create(Application.persistentDataPath + "/data.dat");
- if(data != null){
- data.SetIsGameStartedFirstTIme(isGameStartedFirstTime);
- data.SetIsMusicOn(isMusicOn);
- data.SetHighScore(highScore);
- bf.Serialize(file, data);
- }
- }catch(Exception e){
- Debug.LogException (e, this);
- }finally{
- if(file != null){
- file.Close ();
- }
- }
- }
- public void Load(){
- FileStream file = null;
- try{
- file = File.Open(Application.persistentDataPath + "/data.dat", FileMode.Open);
- data = bf.Deserialize(file) as GameData;
- }catch(Exception e){
- Debug.LogException (e, this);
- }finally{
- if(file != null){
- file.Close ();
- }
- }
- }
- [Serializable]
- class GameData{
- private bool isGameStartedFirstTime;
- private bool isMusicOn;
- private int highScore;
- public void SetIsGameStartedFirstTIme(bool isGameStartedFirstTime){
- this.isGameStartedFirstTime = isGameStartedFirstTime;
- }
- public bool GetIsGameStartedFirstTime(){
- return this.isGameStartedFirstTime;
- }
- public void SetIsMusicOn(bool isMusicOn){
- this.isMusicOn = isMusicOn;
- }
- public bool GetIsMusicOn(){
- return this.isMusicOn;
- }
- public void SetHighScore(int highScore){
- this.highScore = highScore;
- }
- public int GetHighScore(){
- return this.highScore;
- }
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.- public static MusicController instance;
- public AudioClip backgroud;
- public AudioClip gameplay;
- public AudioClip coinRush;
- public AudioClip death;
- public AudioClip start;
- public AudioClip bite;
- [HideInInspector]
- public AudioSource audioSource;
- audioSource = GetComponent<AudioSource> ();
- void CreateInstance(){
- if(instance != null){
- Destroy (gameObject);
- }else{
- instance = this;
- DontDestroyOnLoad (gameObject);
- }
- }
- void Awake(){
- CreateInstance ();
- }
- public void PlayMainMenuBg(){
- if(backgroud){
- audioSource.clip = backgroud;
- audioSource.loop = true;
- audioSource.Play ();
- }
- }
- public void PlayGameplaySound(){
- if(gameplay){
- audioSource.clip = gameplay;
- audioSource.loop = true;
- audioSource.Play ();
- }
- }
- public void PlayCoinRush(){
- if(coinRush){
- if(audioSource.isPlaying){
- audioSource.clip = coinRush;
- audioSource.loop = true;
- audioSource.Play ();
- }
- }
- }
- public void PlayDeathSound(){
- if(death){
- if(!audioSource.isPlaying){
- audioSource.clip = death;
- audioSource.loop = false;
- audioSource.Play ();
- }
- }
- }
- public void PlayStartSound(){
- if(death){
- audioSource.clip = start;
- audioSource.loop = false;
- audioSource.Play ();
- }
- }
- public void StopAllSounds(){
- if(audioSource.isPlaying){
- audioSource.Stop ();
- }
- }
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.- public GameObject exitPanel;
- // Use this for initialization
- void Start () {
- if (GameController.instance.isMusicOn) {
- MusicController.instance.PlayMainMenuBg ();
- } else {
- MusicController.instance.StopAllSounds ();
- }
- }
- // Update is called once per frame
- void Update () {
- if(Input.GetKeyDown(KeyCode.Escape)){
- if (!exitPanel.activeInHierarchy) {
- exitPanel.SetActive (true);
- } else {
- exitPanel.SetActive (false);
- }
- }
- }
- public void StartButton(){
- if(GameController.instance != null){
- GameController.instance.isGameStartedInMainMenu = true;
- }
- SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 1);
- }
- public void YesButton(){
- Application.Quit ();
- }
- public void NoButton(){
- exitPanel.SetActive (false);
- }
- using UnityEngine.UI;
- 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. 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. 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. To make the Background Image locate your sprite from the Game UI directory then add it to the Background GameObject as a component. 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.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
Exit Panel
Text
Buttons
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.- Click the sprite and rename it as Player.
- Open the Animation Pane
- Click Create New Clip name it as Player Move, and save the animation in the Player folder.
- Drag the rest of the sprite in the Animation Pane. Set a 5 seconds delay to each sprite to have a better animation.
- Click Play to animate the sprite.
- After you save the animation the animation. Locate the Player Death sprite and name it Player Death, then drag it to Scene View.
- 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.
- Click the sprite and rename it as Red Enemy, this will be the base sprite.
- 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.
- Open the Animation Pane.
- 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.
- Click Create New Clip name it as Red Right to indicate the sprite name, and save the animation in the Red Enemy folder.
- Click Play to animate the sprite.
- Do the same to the other Red Enemy sprite and save it in the Red Enemy folder, and then delete the GameObjects afterward.
- For the other enemies just do the same as what you did on the Red Enemy, and also for the Afraid and Pale.
- Click the sprite and name it as Coin.
- Open the Animation Pane.
- Click Create New Clip name it as Coin Animation, and save the animation in the Coins folder.
- Drag the rest of the sprite in the Animation Pane, and set a 5 seconds delay to each sprite to have an accurate animation.
- 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 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. 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. In the Background create a UI GameObject as shown in the image. 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. The result will look like these: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. 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. 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- public bool isTeleporter;
- public bool isHouseEntrance;
- public bool isHouse;
- public GameObject gateWay;
- public Intersect[] nearestIntersect;
- public Vector2[] possibleDirection;
- for(int i = 0; i < nearestIntersect.Length; i++){
- Intersect intersection = nearestIntersect [i];
- Vector2 temp = intersection.transform.localPosition - transform.localPosition;
- possibleDirection [i] = temp.normalized;
- }
- Drag now the Coins that can be Intersect to the other Coins in the Intersect script.
- Then duplicate one of the Coins in the Intersect then place it as shown in the image, then remove the Sprite Renderer component. Note: To make the GameObject like in the image above, just click the object beside the GameObject name.
- 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.
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.
- Check the In House Entrance in the Intersect script.
- Also check the In House in the Intersect script that is inside the maze
- 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. 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.
- Create a script namely Coins and attach it to Coins, write these certain variables inside the Coins class.
- public bool silverCoin;
- public bool goldCoin;
- public bool didGet;
- Check Silver Coin if the color of coin is silver or check Gold Coin if the color of coin is gold.
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:- public Vector2 position;
- public float speed = 6f;
- public Sprite idle;
- public Sprite standby;
- public AudioClip getCoin;
- public bool canMove;
- public RuntimeAnimatorController moveAnimation;
- public RuntimeAnimatorController deathAnimation;
- public Button leftButton, rightButton, downButton, upButton;
- private AudioSource audioSource;
- private Vector2 direction;
- private Vector2 nextMove;
- private float flipPosition;
- private Intersect currentPosition, previousPosition, targetPosition;
- private Intersect startingPosition;
- // Use this for initialization
- void Start () {
- InitializePlayerVariables ();
- }
- public void Restart(){
- canMove = true;
- transform.GetComponent<Animator> ().runtimeAnimatorController = moveAnimation
- transform.GetComponent<Animator> ().enabled = true;
- transform.GetComponent<SpriteRenderer> ().enabled = true;
- transform.position = startingPosition.transform.position;
- currentPosition = startingPosition;
- direction = Vector2.left;
- position = Vector2.left;
- nextMove = Vector2.left;
- ChangePosition (direction);
- }
- // Update is called once per frame
- void Update () {
- if (canMove) {
- PlayerMovement ();
- }
- }
- void InitializePlayerVariables(){
- audioSource = GetComponent<AudioSource> ();
- Intersect intersect = GetIntersectPosition (transform.localPosition);
- startingPosition = intersect;
- if(intersect != null){
- currentPosition = intersect;
- }
- direction = Vector2.left;
- position = Vector2.left;
- ChangePosition (direction);
- }
- void PlayerMovement(){
- PlayerInput ();
- Move ();
- UpdatePosition ();
- UpdateAnimationState ();
- GetCoins ();
- }
- void PlayerInput(){
- if(Application.platform == RuntimePlatform.Android){
- TouchScreen ();
- }else if(Application.platform == RuntimePlatform.WindowsEditor){
- KeyboardInput ();
- }
- }
- void KeyboardInput(){
- if(Input.GetKeyDown(KeyCode.LeftArrow)){
- ChangePosition (Vector2.left);
- }else if(Input.GetKeyDown(KeyCode.RightArrow)){
- ChangePosition (Vector2.right);
- }else if(Input.GetKeyDown(KeyCode.UpArrow)){
- ChangePosition (Vector2.up);
- }else if(Input.GetKeyDown(KeyCode.DownArrow)){
- ChangePosition (Vector2.down);
- }
- }
- void TouchScreen(){
- leftButton.onClick.AddListener (() => ChangePosition (Vector2.left));
- rightButton.onClick.AddListener (() => ChangePosition (Vector2.right));
- upButton.onClick.AddListener (() => ChangePosition (Vector2.up));
- downButton.onClick.AddListener (() => ChangePosition (Vector2.down));
- }
- void ChangePosition(Vector2 direction){
- if(direction != this.direction){
- nextMove = direction;
- }
- if(currentPosition != null){
- Intersect moveToIntersect = CanMove (direction);
- if(moveToIntersect != null){
- this.direction = direction;
- targetPosition = moveToIntersect;
- previousPosition = currentPosition;
- currentPosition = null;
- }
- }
- }
- void Move(){
- if(targetPosition != currentPosition && targetPosition != null){
- if(nextMove == direction * -1){
- direction *= -1;
- Intersect temp = targetPosition;
- targetPosition = previousPosition;
- previousPosition = temp;
- }
- if (CheckDetection ()) {
- currentPosition = targetPosition;
- transform.localPosition = currentPosition.transform.position;
- GameObject nextTeleporter = GetTeleporter (currentPosition.transform.position);
- if(nextTeleporter != null){
- transform.localPosition = nextTeleporter.transform.position;
- currentPosition = nextTeleporter.GetComponent<Intersect> ();
- }
- Intersect moveToIntersect = CanMove (nextMove);
- if (moveToIntersect != null) {
- direction = nextMove;
- }
- if (moveToIntersect == null) {
- moveToIntersect = CanMove (direction);
- }
- if (moveToIntersect != null) {
- targetPosition = moveToIntersect;
- previousPosition = currentPosition;
- currentPosition = null;
- } else {
- direction = Vector2.zero;
- }
- } else {
- transform.localPosition += (Vector3)(direction * speed) * Time.deltaTime;
- }
- }
- }
- void MoveToIntersect(Vector2 direction){
- Intersect moveToIntersect = CanMove (direction);
- if(moveToIntersect != null){
- transform.localPosition = moveToIntersect.transform.position;
- currentPosition = moveToIntersect;
- }
- }
- void UpdatePosition(){
- if(direction == Vector2.left){
- position = Vector2.left;
- flipPosition = transform.localScale.x;
- transform.localRotation = Quaternion.Euler (0, 0, 0);
- }else if(direction == Vector2.right){
- position = Vector2.right;
- flipPosition = transform.localScale.x;
- transform.localRotation = Quaternion.Euler (0, 0, 0);
- }else if(direction == Vector2.up){
- position = Vector2.up;
- if (flipPosition == 1) {
- transform.localRotation = Quaternion.Euler (0, 0, -90);
- } else if(flipPosition == -1) {
- transform.localRotation = Quaternion.Euler (0, 0, 90);
- }
- }else if(direction == Vector2.down){
- position = Vector2.down;
- if(flipPosition == 1){
- transform.localRotation = Quaternion.Euler (0, 0, 90);
- }else if(flipPosition == -1){
- transform.localRotation = Quaternion.Euler (0, 0, -90);
- }
- }
- }
- void UpdateAnimationState(){
- if (direction == Vector2.zero) {
- GetComponent<Animator> ().enabled = false;
- GetComponent<SpriteRenderer> ().sprite = idle;
- } else {
- GetComponent<Animator> ().enabled = true;
- }
- }
- public void GetBite(){
- if(GameController.instance != null && MusicController.instance != null){
- if(GameController.instance.isMusicOn){
- audioSource.PlayOneShot (MusicController.instance.bite);
- }
- }
- }
- void GetCoins(){
- GameObject newObj = GetPathPosition (transform.position);
- if(newObj != null){
- Coins coin = newObj.GetComponent<Coins> ();
- if(coin != null){
- if(!coin.didGet && (coin.silverCoin || coin.goldCoin)){
- newObj.GetComponent<SpriteRenderer> ().enabled = false;
- coin.didGet = true;
- GameplayController.instance.coins++;
- if(GameController.instance != null){
- GameController.instance.currentScore += 10;
- }
- if(coin.goldCoin){
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.GetComponent<EnemyController> ().StartAfraidMode ();
- }
- }
- if (GameController.instance != null && MusicController.instance != null) {
- if (GameController.instance.isMusicOn) {
- audioSource.PlayOneShot (getCoin);
- }
- }
- }
- }
- }
- }
- private Intersect CanMove(Vector2 direction){
- Intersect moveToIntersect = null;
- for(int i = 0; i < currentPosition.nearestIntersect.Length; i++){
- if(currentPosition.possibleDirection[i] == direction){
- moveToIntersect = currentPosition.nearestIntersect [i];
- break;
- }
- }
- return moveToIntersect;
- }
- private GameObject GetPathPosition(Vector2 position){
- int x = Mathf.RoundToInt (position.x);
- int y = Mathf.RoundToInt (position.y);
- GameObject path = GameplayController.instance.gameSize[x, y];
- if(path != null){
- return path;
- }
- return null;
- }
- private Intersect GetIntersectPosition(Vector2 position){
- GameObject path = GameplayController.instance.gameSize [(int)position.x, (int)position.y];
- if (path != null) {
- return path.GetComponent<Intersect>();
- }
- return null;
- }
- private bool CheckDetection(){
- float intersectToTarget = LengthFromIntersect (targetPosition.transform.position);
- float intersectToCurrent = LengthFromIntersect (transform.localPosition);
- return intersectToCurrent > intersectToTarget;
- }
- private float LengthFromIntersect(Vector2 targetPosition){
- Vector2 temp = targetPosition - (Vector2)previousPosition.transform.position;
- return temp.sqrMagnitude;
- }
- private GameObject GetTeleporter(Vector2 position){
- GameObject path = GameplayController.instance.gameSize [(int)position.x, (int)position.y];
- if(path != null){
- if (path.GetComponent<Intersect> () != null) {
- if (path.GetComponent<Intersect> ().isTeleporter) {
- GameObject nextTeleporter = path.GetComponent<Intersect> ().gateWay;
- return nextTeleporter;
- }
- }
- }
- return null;
- }
- First attach the script to the Player Component.
- Set the Player position to X=18 and Y=13.
- Add an Animator component in the Inspector.
- Add also an Audio Source component.
- Lastly, attach all the needed Components in the Inspector of PlayerController script.
- 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:- [HideInInspector]
- public float moveSpeed = 5.9f;
- public enum Mode{
- Chase,
- Running,
- Afraid,
- Eaten
- }
- [HideInInspector]
- public float normalSpeed = 5.9f;
- [HideInInspector]
- public float afraidSpeed = 2.9f;
- [HideInInspector]
- public float eatenSpeed = 15f;
- [HideInInspector]
- public int yellowRelease= 5;
- [HideInInspector]
- public int purpleRelease = 15;
- [HideInInspector]
- public int greenRelease = 20;
- [HideInInspector]
- public float releaseTimer = 0;
- [HideInInspector]
- public int afraidDuration = 10;
- [HideInInspector]
- public int blinkingStartTime = 7;
- public bool isInHouse = false;
- public bool canMove;
- public Intersect startingPosition;
- public Intersect runningHome;
- public Intersect house;
- [HideInInspector]
- public int runningModeTimer1 = 7;
- [HideInInspector]
- public int chaseModeTimer1 = 20;
- [HideInInspector]
- public int runningModeTimer2 = 7;
- [HideInInspector]
- public int chaseModeTimer2 = 20;
- [HideInInspector]
- public int runningModeTimer3 = 5;
- [HideInInspector]
- public int chaseModeTimer3 = 20;
- [HideInInspector]
- public int runningModeTimer4 = 5;
- [HideInInspector]
- public int chaseModeTimer4 = 20;
- public Sprite eyesUp;
- public Sprite eyesLeft;
- public Sprite eyesDown;
- public Sprite eyesRight;
- public RuntimeAnimatorController moveUp;
- public RuntimeAnimatorController moveDown;
- public RuntimeAnimatorController moveLeft;
- public RuntimeAnimatorController moveRight;
- public RuntimeAnimatorController pale;
- public RuntimeAnimatorController afraid;
- public enum GhostType{
- Red,
- Yellow,
- Purple,
- Green
- }
- public GhostType ghostType = GhostType.Red;
- private Mode currentMode = Mode.Running;
- private Mode previousMode;
- private int changeModeCounter = 1;
- private float modeTimer = 0;
- private float afraidTimer = 0;
- private float blinkingTimer = 0;
- private bool afraidModeToPale = false;
- private GameObject player;
- private Intersect currentPosition, targetPosition, previousPosition;
- private Vector2 direction, nextDirection;
- private float previousSpeed;
- // Use this for initialization
- void Start () {
- player = GameObject.FindGameObjectWithTag ("Player");
- Intersect intersect = GetIntersectPosition (transform.localPosition);
- if(intersect != null){
- currentPosition = intersect;
- }
- if (isInHouse) {
- direction = Vector2.up;
- targetPosition = currentPosition.nearestIntersect [0];
- } else {
- direction = Vector2.left;
- targetPosition = ChooseNextDirection ();
- }
- previousPosition = currentPosition;
- UpdateAnimatorController ();
- }
- public void Restart(){
- canMove = true;
- transform.GetComponent<SpriteRenderer> ().enabled = true;
- transform.position = startingPosition.transform.position;
- currentMode = Mode.Running;
- releaseTimer = 0;
- changeModeCounter = 1;
- modeTimer = 0;
- moveSpeed = normalSpeed;
- previousSpeed = 0;
- if(transform.name != "Red Enemy"){
- isInHouse = true;
- }
- currentPosition = startingPosition;
- if (isInHouse) {
- direction = Vector2.up;
- targetPosition = currentPosition.nearestIntersect [0];
- } else {
- direction = Vector2.left;
- targetPosition = ChooseNextDirection ();
- }
- previousPosition = currentPosition;
- UpdateAnimatorController ();
- }
- // Update is called once per frame
- void Update () {
- if(canMove){
- ModeUpdate ();
- Move ();
- ReleaseEnemy ();
- CheckCollission ();
- CheckIsInHouse ();
- }
- }
- void CheckIsInHouse(){
- if(currentMode == Mode.Eaten){
- GameObject path = GetPathPosition (transform.position);
- if(path != null){
- if(path.transform.GetComponent<Intersect>() != null){
- if(path.transform.GetComponent<Intersect>().isHouse){
- moveSpeed = normalSpeed;
- Intersect intersect = GetIntersectPosition (transform.position);
- if(intersect != null){
- currentPosition = intersect;
- direction = Vector2.up;
- targetPosition = currentPosition.nearestIntersect [0];
- previousPosition = currentPosition;
- currentMode = Mode.Chase;
- UpdateAnimatorController ();
- }
- }
- }
- }
- }
- }
- void CheckCollission(){
- Rect enemyRect = new Rect (transform.position, transform.GetComponent<SpriteRenderer>().sprite.bounds.size / 4);
- Rect playerRect = new Rect (player.transform.position, player.transform.GetComponent<SpriteRenderer>().sprite.bounds.size / 4);
- if(enemyRect.Overlaps(playerRect)){
- if (currentMode == Mode.Afraid) {
- Eaten ();
- }else if(currentMode == Mode.Running || currentMode == Mode.Chase){
- GameplayController.instance.PlayerDied ();
- }
- }
- }
- void Eaten(){
- GameplayController.instance.counter++;
- GameController.instance.currentScore += GameplayController.instance.ScoreCounter (GameplayController.instance.counter);
- GameplayController.instance.StartConsumed (this.GetComponent<EnemyController> ());
- currentMode = Mode.Eaten;
- previousSpeed = moveSpeed;
- moveSpeed = eatenSpeed;
- UpdateAnimatorController ();
- }
- void UpdateAnimatorController(){
- if (currentMode != Mode.Afraid && currentMode != Mode.Eaten) {
- if (direction == Vector2.up) {
- transform.GetComponent<Animator> ().runtimeAnimatorController = moveUp;
- } else if (direction == Vector2.down) {
- transform.GetComponent<Animator> ().runtimeAnimatorController = moveDown;
- } else if (direction == Vector2.left) {
- transform.GetComponent<Animator> ().runtimeAnimatorController = moveLeft;
- } else if (direction == Vector2.right) {
- transform.GetComponent<Animator> ().runtimeAnimatorController = moveRight;
- } else {
- transform.GetComponent<Animator> ().runtimeAnimatorController = moveLeft;
- }
- }
- else if (currentMode == Mode.Afraid) {
- transform.GetComponent<Animator> ().runtimeAnimatorController = afraid;
- }else if (currentMode == Mode.Eaten) {
- transform.GetComponent<Animator> ().runtimeAnimatorController = null;
- if (direction == Vector2.up) {
- transform.GetComponent<SpriteRenderer> ().sprite = eyesUp;
- } else if (direction == Vector2.down) {
- transform.GetComponent<SpriteRenderer> ().sprite = eyesDown;
- } else if (direction == Vector2.left) {
- transform.GetComponent<SpriteRenderer> ().sprite = eyesLeft;
- } else if (direction == Vector2.right) {
- transform.GetComponent<SpriteRenderer> ().sprite = eyesRight;
- }
- }
- }
- void Move(){
- if(targetPosition != currentPosition && targetPosition != null && !isInHouse){
- if (CheckDetection()) {
- currentPosition = targetPosition;
- transform.localPosition = currentPosition.transform.position;
- GameObject otherTeleporter = GetTeleporter (currentPosition.transform.position);
- if (otherTeleporter != null) {
- transform.localPosition = otherTeleporter.transform.position;
- currentPosition = otherTeleporter.GetComponent<Intersect> ();
- }
- targetPosition = ChooseNextDirection ();
- previousPosition = currentPosition;
- currentPosition = null;
- UpdateAnimatorController ();
- } else {
- transform.localPosition += (Vector3)direction * moveSpeed * Time.deltaTime;
- }
- }
- }
- void ModeUpdate(){
- if (currentMode != Mode.Afraid) {
- modeTimer += Time.deltaTime;
- if (changeModeCounter == 1) {
- if (currentMode == Mode.Running && modeTimer > runningModeTimer1) {
- ChangeMode (Mode.Chase);
- modeTimer = 0;
- }
- if (currentMode == Mode.Chase && modeTimer > chaseModeTimer1) {
- changeModeCounter = 2;
- ChangeMode (Mode.Running);
- modeTimer = 0;
- }
- } else if (changeModeCounter == 2) {
- if(currentMode == Mode.Running && modeTimer > runningModeTimer2){
- ChangeMode (Mode.Chase);
- modeTimer = 0;
- }
- if(currentMode == Mode.Chase && modeTimer > chaseModeTimer2){
- changeModeCounter = 3;
- ChangeMode (Mode.Running);
- modeTimer = 0;
- }
- } else if (changeModeCounter == 3) {
- if(currentMode == Mode.Running && modeTimer > runningModeTimer3){
- ChangeMode (Mode.Chase);
- modeTimer = 0;
- }
- if(currentMode == Mode.Chase && modeTimer > chaseModeTimer3){
- changeModeCounter = 4;
- ChangeMode (Mode.Running);
- modeTimer = 0;
- }
- } else if (changeModeCounter == 4) {
- if(currentMode == Mode.Running && modeTimer > runningModeTimer4){
- ChangeMode (Mode.Chase);
- modeTimer = 0;
- }
- }
- } else if(currentMode == Mode.Afraid){
- afraidTimer += Time.deltaTime;
- if(afraidTimer >= afraidDuration){
- afraidTimer = 0;
- ChangeMode (previousMode);
- if (MusicController.instance != null && GameController.instance != null) {
- if (GameController.instance.isMusicOn) {
- MusicController.instance.PlayGameplaySound ();
- }
- }
- }
- if(afraidTimer >= blinkingStartTime){
- blinkingTimer += Time.deltaTime;
- if(blinkingTimer >= 0.1f){
- blinkingTimer = 0;
- if (afraidModeToPale) {
- transform.GetComponent<Animator> ().runtimeAnimatorController = afraid;
- afraidModeToPale = false;
- } else {
- transform.GetComponent<Animator> ().runtimeAnimatorController = pale;
- afraidModeToPale = true;
- }
- }
- }
- }
- }
- void ChangeMode(Mode m){
- if(currentMode == Mode.Afraid){
- moveSpeed = previousSpeed;
- }
- if(m == Mode.Afraid){
- previousSpeed = moveSpeed;
- moveSpeed = afraidSpeed;
- }
- if(currentMode != m){
- previousMode = currentMode;
- currentMode = m;
- }
- UpdateAnimatorController ();
- }
- public void StartAfraidMode(){
- if(currentMode != Mode.Eaten){
- afraidTimer = 0;
- GameplayController.instance.counter = 0;
- ChangeMode (Mode.Afraid);
- }
- if (GameController.instance != null && MusicController.instance != null) {
- if (GameController.instance.isMusicOn) {
- MusicController.instance.PlayCoinRush ();
- }
- }
- }
- Vector2 GetRedTargetPos(){
- Vector2 playerPosition = player.transform.localPosition;
- Vector2 targetPath = new Vector2 (Mathf.RoundToInt (playerPosition.x), Mathf.RoundToInt (playerPosition.y));
- return targetPath;
- }
- Vector2 GetYellowTargetPos(){
- Vector2 playerPosition = player.transform.localPosition;
- Vector2 playerOrientation = player.GetComponent<PlayerController> ().position;
- int playerPositionX = Mathf.RoundToInt (playerPosition.x);
- int playerPositionY = Mathf.RoundToInt (playerPosition.y);
- Vector2 targetPath = playerPath + (4 * playerOrientation);
- return targetPath;
- }
- Vector2 GetPurpleTargetPos(){
- Vector2 playerPosition = player.transform.localPosition;
- Vector2 playerOrientation = player.GetComponent<PlayerController> ().position;
- int playerPositionX = Mathf.RoundToInt (playerPosition.x);
- int playerPositionY = Mathf.RoundToInt (playerPosition.y);
- Vector2 targetPath = playerPath + (2 * playerOrientation);
- Vector2 tempPosition = GameObject.Find ("Red Enemy").transform.localPosition;
- int PurplePositionX = Mathf.RoundToInt (tempPosition.x);
- int PurplePositionY = Mathf.RoundToInt (tempPosition.y);
- float distance = GetDistance (tempPosition, targetPath);
- distance *= 2;
- return targetPath;
- }
- Vector2 GetGreenTargetPos(){
- Vector2 playerPosition = player.transform.localPosition;
- float distance = GetDistance (transform.localPosition, playerPosition);
- Vector2 targetPath = Vector2.zero;
- if(distance >= 8){
- targetPath = new Vector2 (Mathf.RoundToInt (playerPosition.x), Mathf.RoundToInt (playerPosition.y));
- }else if(distance <= 8){
- targetPath = runningHome.transform.position;
- }
- return targetPath;
- }
- Vector2 GetTargetPath(){
- Vector2 targetPath = Vector2.zero;
- if(ghostType == GhostType.Red){
- targetPath = GetRedTargetPos ();
- }else if(ghostType == GhostType.Yellow){
- targetPath = GetYellowTargetPos ();
- }else if(ghostType == GhostType.Purple){
- targetPath = GetPurpleTargetPos ();
- }else if(ghostType == GhostType.Green){
- targetPath = GetGreenTargetPos ();
- }
- return targetPath;
- }
- Vector2 GetRandomPath(){
- int x = Random.Range (0, 28);
- int y = Random.Range (0, 36);
- }
- void ReleaseYellow(){
- if(ghostType == GhostType.Yellow && isInHouse){
- isInHouse = false;
- }
- }
- void ReleasePurple(){
- if(ghostType == GhostType.Purple && isInHouse){
- isInHouse = false;
- }
- }
- void ReleaseGreen(){
- if(ghostType == GhostType.Green && isInHouse){
- isInHouse = false;
- }
- }
- void ReleaseEnemy(){
- releaseTimer += Time.deltaTime;
- if(releaseTimer > yellowRelease){
- ReleaseYellow ();
- }
- if(releaseTimer > purpleRelease){
- ReleasePurple ();
- }
- if(releaseTimer > greenRelease){
- ReleaseGreen ();
- }
- }
- private Intersect ChooseNextDirection(){
- Vector2 targetPath = Vector2.zero;
- if(currentMode == Mode.Chase){
- targetPath = GetTargetPath ();
- }else if(currentMode == Mode.Running){
- targetPath = runningHome.transform.position;
- }else if(currentMode == Mode.Afraid){
- targetPath = GetRandomPath ();
- }else if(currentMode == Mode.Eaten){
- targetPath = house.transform.position;
- }
- Intersect moveToIntersect = null;
- int intersectCounter = 0;
- for(int i = 0; i < currentPosition.nearestIntersect.Length; i++){
- if(currentPosition.possibleDirection[i] != direction *-1){
- if (currentMode != Mode.Eaten) {
- GameObject path = GetPathPosition (currentPosition.transform.position);
- if (path.transform.GetComponent<Intersect> ().isHouseEntrance == true) {
- if (currentPosition.possibleDirection [i] != Vector2.down) {
- foundIntersection [intersectCounter] = currentPosition.nearestIntersect [i];
- foundIntersectDirection [intersectCounter] = currentPosition.possibleDirection [i];
- intersectCounter++;
- }
- } else {
- foundIntersection [intersectCounter] = currentPosition.nearestIntersect [i];
- foundIntersectDirection [intersectCounter] = currentPosition.possibleDirection [i];
- intersectCounter++;
- }
- } else {
- foundIntersection [intersectCounter] = currentPosition.nearestIntersect [i];
- foundIntersectDirection [intersectCounter] = currentPosition.possibleDirection [i];
- intersectCounter++;
- }
- }
- }
- if(foundIntersection.Length == 1){
- moveToIntersect = foundIntersection [0];
- direction = foundIntersectDirection [0];
- }
- if(foundIntersection.Length > 1){
- float leastDistance = 100000f;
- for (int i = 0; i < foundIntersection.Length; i++) {
- if(foundIntersectDirection[i] != Vector2.zero){
- float distance = GetDistance (foundIntersection [i].transform.position, targetPath);
- if(distance < leastDistance){
- leastDistance = distance;
- moveToIntersect = foundIntersection [i];
- direction = foundIntersectDirection [i];
- }
- }
- }
- }
- return moveToIntersect;
- }
- private Intersect GetIntersectPosition(Vector2 position){
- GameObject path = GameplayController.instance.gameSize [(int)position.x, (int)position.y];
- if(path != null){
- if(path.GetComponent<Intersect>() != null){
- return path.GetComponent<Intersect> ();
- }
- }
- return null;
- }
- private GameObject GetPathPosition(Vector2 position){
- int pathX = Mathf.RoundToInt (position.x);
- int pathY = Mathf.RoundToInt (position.y);
- GameObject path = GameplayController.instance.gameSize [pathX, pathY];
- if(path != null){
- return path;
- }
- return null;
- }
- private GameObject GetTeleporter(Vector2 pos){
- GameObject path = GameplayController.instance.gameSize [(int)pos.x, (int)pos.y];
- if(path != null){
- if(path.GetComponent<Intersect>().isTeleporter){
- GameObject otherTeleporter = path.GetComponent<Intersect> ().gateWay;
- return otherTeleporter;
- }
- }
- return null;
- }
- private float LengthFromIntersect(Vector2 targetPosition){
- Vector2 temp = targetPosition - (Vector2)previousPosition.transform.position;
- return temp.sqrMagnitude;
- }
- private bool CheckDetection(){
- float intersectToTarget = LengthFromIntersect (targetPosition.transform.position);
- float intersectToCurrent = LengthFromIntersect (transform.localPosition);
- return intersectToCurrent > intersectToTarget;
- }
- private float GetDistance(Vector2 dist1, Vector2 dist2){
- float x = dist1.x - dist2.x;
- float y = dist1.y - dist2.y;
- float distance = Mathf.Sqrt (x * x + y * y);
- return distance;
- }
- First attach the script to each Enemy components; Red Enemy, Yellow Enemy, Purple Enemy and Green Enemy.
- Set each Enemies Transform and Tag them as Enemy shown in the image below.
- Add an Animator to each enemy component.
- Drag and assign each corresponding component to EnemyController script inspector.
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:- public static GameplayController instance;
- public GameObject pausePanel;
- public int totalCoins;
- public int score;
- public int highScore;
- public int maxLive;
- public Text readyText;
- public Text highscoreText;
- public Text enemyScoreText;
- public Text scoreText;
- public Text blinkingScore;
- public Image[] liveSprites;
- public int coins;
- [HideInInspector]
- public int scoreCounter;
- [HideInInspector]
- public int counter;
- private bool gameInProgress, gameInPause;
- private bool isDied;
- private bool isStartEat;
- private bool newHighscore;
- private static int width = 28;
- private static int height = 36;
- private int lives;
- using UnityEngine.UI;
- using UnityEngine.SceneManagement;
- void Awake(){
- CreateInstance ();
- }
- // Use this for initialization
- void Start () {
- InitializeGameplayVariables ();
- StartGame ();
- }
- // Update is called once per frame
- void Update () {
- UpdateGameplay ();
- }
- void UpdateGameplay(){
- if(GameController.instance != null){
- score = GameController.instance.currentScore;
- scoreText.text = score.ToString("N0");
- if(GameController.instance.currentScore >= GameController.instance.highScore){
- GameController.instance.highScore = score;
- highScore = GameController.instance.highScore;
- highscoreText.text = highScore.ToString ("N0");
- GameController.instance.Save ();
- }
- }
- CheckCoins ();
- }
- void CreateInstance(){
- if(instance == null){
- instance = this;
- }
- }
- void InitializeGameplayVariables(){
- InitializeGameSize ();
- if(GameController.instance != null){
- if (GameController.instance.isGameStartedInMainMenu) {
- lives = maxLive - 1;
- GameController.instance.currentLives = lives;
- GameController.instance.currentScore = 0;
- score = GameController.instance.currentScore;
- highScore = GameController.instance.highScore;
- scoreText.text = score.ToString ("N0");
- highscoreText.text = highScore.ToString ("N0");
- GameController.instance.isGameStartedInMainMenu = false;
- }else {
- lives = GameController.instance.currentLives;
- score = GameController.instance.currentScore;
- highScore = GameController.instance.highScore;
- scoreText.text = score.ToString ("N0");
- highscoreText.text = highScore.ToString ("N0");
- }
- }
- for(int i = 0; i < maxLive; i++){
- if (lives > i) {
- liveSprites [i].gameObject.SetActive (true);
- } else {
- liveSprites [i].gameObject.SetActive (false);
- }
- }
- }
- void CheckCoins(){
- if(totalCoins == coins){
- LevelComplete ();
- }
- }
- void LevelComplete(){
- StartCoroutine (CompleteTimer (2));
- }
- IEnumerator CompleteTimer(float delay){
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<PlayerController> ().canMove = false;
- player.transform.GetComponent<Animator> ().enabled = false;
- if(GameController.instance != null && MusicController.instance != null){
- if(GameController.instance.isMusicOn){
- MusicController.instance.StopAllSounds ();
- }
- }
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<EnemyController> ().canMove = false;
- enemy.transform.GetComponent<Animator> ().enabled = false;
- }
- StartCoroutine (PrepareNextLevel (2));
- }
- IEnumerator PrepareNextLevel(float delay){
- if(GameController.instance != null){
- GameController.instance.currentLevel++;
- }
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<SpriteRenderer> ().enabled = false;
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<SpriteRenderer> ().enabled = false;
- }
- StartNextLevel ();
- }
- void StartNextLevel(){
- if (SceneManager.GetActiveScene ().buildIndex == SceneManager.sceneCountInBuildSettings - 1) {
- StartCoroutine (FinishAllLevel (5));
- } else {
- if(GameController.instance != null){
- SceneManager.LoadScene ("Level " + GameController.instance.currentLevel);
- }
- }
- }
- IEnumerator FinishAllLevel(float delay){
- readyText.text = "LEVEL COMPLETED";
- readyText.color = Color.blue;
- readyText.gameObject.SetActive (true);
- SceneManager.LoadScene ("Main Menu");
- }
- void InitializeGameSize(){
- foreach(GameObject newObj in obj){
- Vector2 position = newObj.transform.position;
- 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")) {
- if(newObj.GetComponent<Coins>() != null){
- if(newObj.GetComponent<Coins>().silverCoin || newObj.GetComponent<Coins>().goldCoin ){
- totalCoins++;
- }
- }
- gameSize [(int)position.x, (int)position.y] = newObj;
- }
- }
- }
- public void StartConsumed(EnemyController consumed){
- if(!isStartEat){
- StopAllCoroutines ();
- isStartEat = true;
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<EnemyController> ().canMove = false;
- }
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<PlayerController> ().canMove = false;
- player.transform.GetComponent<SpriteRenderer> ().enabled = false;
- consumed.transform.GetComponent<SpriteRenderer> ().enabled = false;
- if(GameController.instance != null && MusicController.instance != null){
- if(GameController.instance.isMusicOn){
- MusicController.instance.audioSource.Stop ();
- }
- }
- Vector2 position = consumed.transform.position;
- Vector2 viewPortPoint = Camera.main.WorldToViewportPoint (position);
- enemyScoreText.GetComponent<RectTransform> ().anchorMin = viewPortPoint;
- enemyScoreText.GetComponent<RectTransform> ().anchorMax = viewPortPoint;
- enemyScoreText.text = ScoreCounter (counter).ToString ();
- enemyScoreText.gameObject.SetActive (true);
- if(GameController.instance != null){
- if(GameController.instance.isMusicOn){
- player.transform.GetComponent<PlayerController> ().GetBite ();
- }
- }
- StartCoroutine (ProcessConsumed (0.75f, consumed));
- }
- }
- public int ScoreCounter(int counter){
- switch(counter){
- case 1:
- scoreCounter = 200;
- break;
- case 2:
- scoreCounter = 400;
- break;
- case 3:
- scoreCounter = 800;
- break;
- case 4:
- scoreCounter = 1600;
- break;
- }
- return scoreCounter;
- }
- IEnumerator StartBlinking(Text blinkingText){
- blinkingText.GetComponent<Text>().enabled = !blinkingText.GetComponent<Text>().enabled;
- StartCoroutine (StartBlinking (blinkingText));
- }
- IEnumerator ProcessConsumed(float delay, EnemyController consumed){
- enemyScoreText.gameObject.SetActive (false);
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<SpriteRenderer> ().enabled = true;
- consumed.transform.GetComponent<SpriteRenderer> ().enabled = true;
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<EnemyController> ().canMove = true;
- }
- player.transform.GetComponent<PlayerController> ().canMove = true;
- if(GameController.instance != null && MusicController.instance != null){
- if(GameController.instance.isMusicOn){
- MusicController.instance.audioSource.Play ();
- }
- }
- isStartEat = false;
- StartCoroutine (StartBlinking (blinkingScore));
- }
- public void StartGame(){
- readyText.gameObject.SetActive (true);
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<SpriteRenderer> ().enabled = false;
- enemy.transform.GetComponent<EnemyController>().canMove = false;
- }
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<Animator> ().enabled = false;
- player.transform.GetComponent<PlayerController> ().canMove = false;
- if(GameController.instance != null && MusicController.instance != null){
- if(GameController.instance.isMusicOn){
- MusicController.instance.PlayStartSound ();
- }else {
- MusicController.instance.StopAllSounds ();
- }
- }
- StartCoroutine (StartGameTimer (3.5f));
- StartCoroutine (StartBlinking (blinkingScore));
- }
- private void RestartGame(){
- readyText.gameObject.SetActive (true);
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<SpriteRenderer> ().enabled = false;
- enemy.transform.GetComponent<EnemyController>().canMove = false;
- }
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<Animator> ().enabled = false;
- player.transform.GetComponent<SpriteRenderer> ().sprite = player.transform.GetComponent<PlayerController> ().standby;
- player.transform.GetComponent<PlayerController> ().canMove = false;
- StartCoroutine (RestartGameTimer (1));
- }
- IEnumerator RestartGameTimer(float delay){
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<SpriteRenderer> ().enabled = true;
- enemy.transform.GetComponent<EnemyController> ().canMove = true;
- }
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<Animator> ().enabled = true;
- player.transform.GetComponent<PlayerController> ().canMove = true;
- readyText.gameObject.SetActive (false);
- if(GameController.instance != null && MusicController.instance != null){
- if(GameController.instance.isMusicOn){
- MusicController.instance.PlayGameplaySound ();
- }
- }
- }
- IEnumerator StartGameTimer(float delay){
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<SpriteRenderer> ().enabled = true;
- enemy.transform.GetComponent<EnemyController> ().canMove = true;
- }
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<Animator> ().enabled = true;
- player.transform.GetComponent<PlayerController> ().canMove = true;
- readyText.gameObject.SetActive (false);
- if (MusicController.instance != null && GameController.instance != null) {
- if (GameController.instance.isMusicOn) {
- MusicController.instance.PlayGameplaySound ();
- }
- }
- gameInProgress = true;
- }
- public void PlayerDied(){
- if(!isDied){
- isDied = true;
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<EnemyController> ().canMove = false;
- }
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<Animator> ().enabled = false;
- player.transform.GetComponent<PlayerController> ().canMove = false;
- if(MusicController.instance != null && GameController.instance != null){
- if (GameController.instance.isMusicOn) {
- MusicController.instance.StopAllSounds ();
- }
- }
- StartCoroutine (PlayerDiedTimer(2));
- }
- }
- IEnumerator PlayerDiedTimer(float delay){
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<SpriteRenderer> ().enabled = false;
- }
- StartCoroutine (DeathAnimation (1.9f));
- }
- IEnumerator DeathAnimation(float delay){
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<Animator>().runtimeAnimatorController = player.transform.GetComponent<PlayerController>().deathAnimation;
- player.transform.GetComponent<Animator> ().enabled = true;
- if(GameController.instance != null && MusicController.instance != null){
- if(GameController.instance.isMusicOn){
- MusicController.instance.PlayDeathSound ();
- }
- }
- StartCoroutine (Restarting (2));
- }
- IEnumerator Restarting(float delay){
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<SpriteRenderer> ().enabled = false;
- RestartLevel ();
- }
- public void RestartLevel(){
- lives -= 1;
- if (lives < 0) {
- readyText.text = "GAME OVER";
- readyText.color = Color.red;
- readyText.gameObject.SetActive (true);
- StartCoroutine (BackToMainMenu (3f));
- } else {
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<PlayerController> ().Restart ();
- player.transform.localRotation = Quaternion.Euler (0, 0, 0);
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<EnemyController> ().Restart();
- }
- isDied = false;
- RestartGame ();
- }
- for(int i = 0; i < maxLive; i++){
- if (lives > i) {
- liveSprites [i].gameObject.SetActive (true);
- } else {
- liveSprites [i].gameObject.SetActive (false);
- }
- }
- }
- IEnumerator BackToMainMenu(float delay){
- SceneManager.LoadScene ("Main Menu");
- }
- public void PauseButton(){
- if(!gameInPause){
- if(gameInProgress){
- gameInPause = true;
- gameInProgress = false;
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<PlayerController> ().canMove = false;
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<EnemyController> ().canMove = false;
- }
- pausePanel.SetActive (true);
- }
- }
- }
- public void ResumeButton(){
- if(gameInPause){
- if(!gameInProgress){
- gameInPause = false;
- gameInProgress = true;
- GameObject player = GameObject.FindGameObjectWithTag ("Player");
- player.transform.GetComponent<PlayerController> ().canMove = true;
- GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
- foreach(GameObject enemy in enemies){
- enemy.transform.GetComponent<EnemyController> ().canMove = true;
- }
- pausePanel.SetActive (false);
- }
- }
- }
- public void QuitButton(){
- SceneManager.LoadScene ("Main Menu");
- }
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.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. After you're done click the Player Setting, then fill up the required information in order to build the application. 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.
Add new comment
- Add new comment
- 434 views