Advertisement
Guest User

Untitled

a guest
Feb 18th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.91 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Tilemaps;
  5. using UnityEngine.UI;
  6. using System.Linq;
  7. using System;
  8.  
  9. public class GameManager : MonoBehaviour
  10. {
  11.     public float levelStartDelay = 1f;                      //Time to wait before starting level, in seconds.
  12.     public float turnDelay = 0.1f;                          //Delay between each Player turn.
  13.     public int playerHealth = 6;                      //Starting value for Player food points.
  14.     public static GameManager instance = null;              //Static instance of GameManager which allows it to be accessed by any other script.
  15.     [HideInInspector]
  16.     public bool playersTurn = true;       //Boolean to check if it's players turn, hidden in inspector but public.
  17.     public bool doingSetup = true;
  18.     public GameObject cube;
  19.     public bool paused = false;
  20.     public int level = 1;
  21.     public LayerMask outlinesLayer;
  22.  
  23.     public Tilemap[] tilemaps;
  24.     public GameObject board;
  25.     public BoardManager boardScript;
  26.  
  27.     private Transform[] tiles;
  28.     private Text levelText;                                 //Text to display current level number.
  29.     private GameObject levelImage;
  30.     //Store a reference to our BoardManager which will set up the level.
  31.     //Current level number, expressed in game as "Day 1".
  32.     public List<Enemy> enemies;                          //List of all Enemy units, used to issue them move commands.
  33.     private bool enemiesMoving;                             //Boolean to check if enemies are moving.
  34.                                                             //Boolean to check if we're setting up board, prevent Player from moving during setup.
  35.     private IEnumerator ClickCoroutine;
  36.  
  37.  
  38.     //Awake is always called before any Start functions
  39.     void Awake()
  40.     {
  41.         //Check if instance already exists
  42.         if (instance == null)
  43.  
  44.             //if not, set instance to this
  45.             instance = this;
  46.  
  47.         //If instance already exists and it's not this:
  48.         else if (instance != this)
  49.  
  50.             //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
  51.             Destroy(gameObject);
  52.  
  53.         //Sets this to not be destroyed when reloading scene
  54.         DontDestroyOnLoad(gameObject);
  55.  
  56.         //Assign enemies to a new List of Enemy objects.
  57.         enemies = new List<Enemy>();
  58.  
  59.         //Get a component reference to the attached BoardManager script
  60.         boardScript = GetComponent<BoardManager>();
  61.  
  62.         //
  63.  
  64.         //Call the InitGame function to initialize the first level
  65.         InitGame();
  66.     }
  67.  
  68.     //This is called each time a scene is loaded.
  69.     void OnLevelWasLoaded(int index)
  70.     {
  71.         //Add one to our level number.
  72.         level++;
  73.         //Call InitGame to initialize our level.
  74.         InitGame();
  75.     }
  76.  
  77.     //Initializes the game for each level.
  78.     void InitGame()
  79.     {
  80.         //While doingSetup is true the player can't move, prevent player from moving while title card is up.
  81.         doingSetup = true;
  82.  
  83.         //Get a reference to our image LevelImage by finding it by name.
  84.         levelImage = GameObject.Find("Level Image");
  85.  
  86.         //Get a reference to our text LevelText's text component by finding it by name and calling GetComponent.
  87.         levelText = GameObject.Find("Level Text").GetComponent<Text>();
  88.  
  89.         //Set the text of levelText to the string "Day" and append the current level number.
  90.         levelText.text = "Depth " + level;
  91.  
  92.         //Set levelImage to active blocking player's view of the game board during setup.
  93.         levelImage.SetActive(true);
  94.  
  95.         //Call the HideLevelImage function with a delay in seconds of levelStartDelay.
  96.         Invoke("HideLevelImage", levelStartDelay);
  97.  
  98.         //Clear any Enemy objects in our List to prepare for next level.
  99.         enemies.Clear();
  100.  
  101.  
  102.  
  103.         Player.instance.transform.position = new Vector3(0, 0);
  104.         Player.instance.enabled = true;
  105.  
  106.         cube = Player.instance.transform.GetChild(0).gameObject;
  107.  
  108.         if (level == 1)
  109.         {
  110.             boardScript.InstantiateTutorialBoard(0);
  111.             board = GameObject.FindGameObjectWithTag("Board");
  112.             tilemaps = board.GetComponentsInChildren<Tilemap>();
  113.             return;
  114.         }
  115.         else if (level == 2)
  116.         {
  117.             boardScript.InstantiateTutorialBoard(1);
  118.             return;
  119.         }
  120.         else
  121.         {
  122.             //Call the SetupScene function of the BoardManager script, pass it current level number.
  123.             boardScript.SetupScene(level);
  124.         }
  125.  
  126.  
  127.     }
  128.  
  129.  
  130.     //Hides black image used between levels
  131.     void HideLevelImage()
  132.     {
  133.         //Disable the levelImage gameObject.
  134.         levelImage.SetActive(false);
  135.  
  136.         //Set doingSetup to false allowing player to move again.
  137.         doingSetup = false;
  138.     }
  139.  
  140.  
  141.     Vector3 st = Vector3.zero;
  142.     Vector3 ed = Vector3.zero;
  143.  
  144.     //Update is called every frame.
  145.     void Update()
  146.     {
  147.  
  148.         Debug.DrawLine(st, ed);
  149.  
  150.         //Check that playersTurn or enemiesMoving or doingSetup are not currently true.
  151.         if (playersTurn || enemiesMoving || doingSetup)
  152.  
  153.             //If any of these are true, return and do not start MoveEnemies.
  154.             return;
  155.  
  156.         //Start moving enemies.
  157.         StartCoroutine(MoveEnemies());
  158.     }
  159.  
  160.     //Call this to add the passed in Enemy to the List of Enemy objects.
  161.     public void AddEnemyToList(Enemy script)
  162.     {
  163.         //Add Enemy to List enemies.
  164.         enemies.Add(script);
  165.     }
  166.  
  167.  
  168.     //GameOver is called when the player reaches 0 food points
  169.     public void GameOver()
  170.     {
  171.         //Set levelText to display number of levels passed and game over message
  172.         levelText.text = "You succumbed to the Die.";
  173.  
  174.         //Enable black background image gameObject.
  175.         levelImage.SetActive(true);
  176.  
  177.         //Disable this GameManager.
  178.         enabled = false;
  179.     }
  180.  
  181.     //Coroutine to move enemies in sequence.
  182.     IEnumerator MoveEnemies()
  183.     {
  184.         //While enemiesMoving is true player is unable to move.
  185.         enemiesMoving = true;
  186.  
  187.         //Wait for turnDelay seconds, defaults to .1 (100 ms).
  188.         yield return new WaitForSeconds(turnDelay);
  189.  
  190.         //If there are no enemies spawned (IE in first level):
  191.         if (enemies.Count == 0)
  192.         {
  193.             //Wait for turnDelay seconds between moves, replaces delay caused by enemies moving when there are none.
  194.             yield return new WaitForSeconds(turnDelay);
  195.         }
  196.  
  197.         //Loop through List of Enemy objects.
  198.         for (int i = 0; i < enemies.Count; i++)
  199.         {
  200.             //Call the MoveEnemy function of Enemy at index i in the enemies List.
  201.             enemies[i].MoveEnemy();
  202.  
  203.             //Wait for Enemy's moveTime before moving next Enemy,
  204.             yield return new WaitForSeconds(enemies[i].moveTime);
  205.         }
  206.         //Once Enemies are done moving, set playersTurn to true so player can move.
  207.         playersTurn = true;
  208.  
  209.         //Enemies are done moving, set enemiesMoving to false.
  210.         enemiesMoving = false;
  211.     }
  212.  
  213.     public void SelectTarget(List<Vector3Int> actablePositions, Item item)
  214.     {
  215.         StartCoroutine(MoveCurrentHighlighted(actablePositions, item));
  216.     }
  217.  
  218.  
  219.  
  220.     IEnumerator MoveCurrentHighlighted(List<Vector3Int> actablePositions, Item item)
  221.     {
  222.         Tilemap outlinesMap = Array.Find(tilemaps, x => x.name == "Outlines"); // the tilemap on which all outlines are drawn
  223.         Vector2Int playerPos = new Vector2Int((int)Player.instance.transform.position.x, (int)Player.instance.transform.position.y); // the position of the player in Vector2Int because tilemaps methods take only Integer as parameters
  224.         Vector2Int currentHighlighted = playerPos; // only for the beginning, put currentHighlighted at a relative (0,0,0)
  225.         Vector2Int previousHighlighted; // a field to store the position that was highlighted in order to switch the sprite to the normal outline
  226.         Vector2Int direction; // the direction that the player wants to go towards when selecting target
  227.         bool selectingTarget = true;
  228.  
  229.         while (selectingTarget) // everyframe, while this is true
  230.         {
  231.             // if the player uses arrows keys
  232.             if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow))
  233.             {
  234.  
  235.                 // typical GetAxis...
  236.                 int horizontal = 0;
  237.                 int vertical = 0;
  238.  
  239.                 horizontal = (int)Input.GetAxisRaw("Horizontal");
  240.                 vertical = (int)Input.GetAxisRaw("Vertical");
  241.  
  242.                 direction = new Vector2Int(horizontal, vertical);
  243.  
  244.                 previousHighlighted = currentHighlighted; // store the position of the currentHighlighted before it changes
  245.  
  246.                 RaycastHit2D hit = Physics2D.Raycast(currentHighlighted+outlinesMap.cellSize.x* (Vector2)direction, direction, 10, outlinesLayer); // Cast a ray from currentHighlighted toward the direction on the outlinesLayer
  247.  
  248.                 st = currentHighlighted + outlinesMap.cellSize.x * (Vector2)direction;
  249.  
  250.                 ed = st + (Vector3)(Vector2)direction * 10f;
  251.  
  252.                 //Debug.Log(hit.collider.name);
  253.  
  254.                 // If the ray hit something, then there is an outline in that direction
  255.                 if (hit.collider != null)
  256.                 {
  257.                     Debug.Log("here");
  258.                     Debug.Log(hit.point);
  259.                     Vector3Int pos = outlinesMap.WorldToCell(hit.point + outlinesMap.cellSize.x / 2f * (Vector2)direction);
  260.                     currentHighlighted = new Vector2Int(pos.x, pos.y);
  261.                     // Until currentHighlight is not equivalent to the position of an outlineTile on the outlinesMap... (Since the ray has hit something on the outlines layer, there should necessarily be an outlineTile in that direction)
  262.                     //while (outlinesMap.GetTile(new Vector3Int(currentHighlighted.x, currentHighlighted.y, 0)) != board.GetComponent<GridInformation>().outlineTile)
  263.                     //    currentHighlighted += direction;
  264.                 }
  265.                 //else if (hit.collider == null) // The ray originating from currentHighlighted has not hit anything, thus there is no outlineTile in that direction
  266.                 //{
  267.                 //    Debug.Log("Recasting from player");
  268.  
  269.                 //    //// Cast a ray toward the direction on the Outlines layer, but this time the origin is the player's position
  270.                 //    //RaycastHit2D hitFromPlayer = Physics2D.Raycast(playerPos, direction, 10, outlinesLayer);
  271.  
  272.                 //    //// If the ray hit something, then there is an outline in that direction
  273.                 //    //if (hitFromPlayer.collider != null)
  274.                 //    //    // Until currentHighlight is not equivalent to the position of an outlineTile on the outlinesMap... (Since the ray has hit something on the outlines layer, there should necessarily be an outlineTile in that direction)
  275.                 //    //    while (outlinesMap.GetTile(new Vector3Int(currentHighlighted.x, currentHighlighted.y, 0)) != board.GetComponent<GridInformation>().outlineTile)
  276.                 //    //        currentHighlighted += direction;
  277.                 //    //else // both rays have not returned anything
  278.                 //    //{
  279.                 //    //    Debug.Log("Both raycasts did not hit anything. There is no available target in that direction");
  280.                 //    //}
  281.  
  282.  
  283.                 //    hit = Physics2D.Raycast(playerPos + direction, direction, 10, outlinesLayer); // Cast a ray from currentHighlighted toward the direction on the outlinesLayer
  284.                 //    if (hit.collider != null)
  285.                 //    {
  286.                 //        Vector3Int pos = outlinesMap.WorldToCell(hit.point);
  287.                 //        currentHighlighted = new Vector2Int(pos.x, pos.y);
  288.                 //    }
  289.                 //    else
  290.                 //    {
  291.                 //        Debug.Log("Both raycasts did not hit anything. There is no available target in that direction");
  292.                 //    }
  293.                 //}
  294.  
  295.                 Debug.Log(currentHighlighted);
  296.  
  297.                 UpdateHighlighted(outlinesMap, previousHighlighted, currentHighlighted);
  298.             }
  299.             else if (Input.GetKeyDown(KeyCode.Space)) // If user presses spacebar, use the action, turn all outlines off and quit the coroutine
  300.             {
  301.                 item.Use(new Vector3Int(currentHighlighted.x, currentHighlighted.y, 0));
  302.                 selectingTarget = false;
  303.                 StopCoroutine(MoveCurrentHighlighted(actablePositions, item));
  304.             }
  305.  
  306.             yield return null;
  307.         }
  308.     }
  309.  
  310.     public void UpdateHighlighted(Tilemap outlinesMap, Vector2Int previousHighlighted, Vector2Int currentHighlighted)
  311.     {
  312.         // if the outlinesMap has a tile at the currentHighlighted...
  313.         if (outlinesMap.HasTile(new Vector3Int(currentHighlighted.x, currentHighlighted.y, 0)))
  314.         {
  315.             // if the outlinesMap has a tile at the previousHighlighted... (this is to make sure that, at the beginning when currentHighlighted is set to the playerPos, the playerPos does not become outlined)
  316.             if (outlinesMap.HasTile(new Vector3Int(previousHighlighted.x, previousHighlighted.y, 0)))
  317.                 // set the previously highlighted outlineTile back to the normal outlineTile
  318.                 outlinesMap.SetTile(new Vector3Int(previousHighlighted.x, previousHighlighted.y, 0), board.GetComponent<GridInformation>().outlineTile);
  319.  
  320.             // Switch the normal outlineTile to the selectedOutlineTile
  321.             outlinesMap.SetTile(new Vector3Int(currentHighlighted.x, currentHighlighted.y, 0), board.GetComponent<GridInformation>().selectedOutlineTile);
  322.         }
  323.     }
  324. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement