Advertisement
SHenryL

GridManager

Sep 15th, 2022
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class GridManager : MonoBehaviour
  6. {
  7.     [SerializeField] Vector2Int gridSize; // specifies x width & y height of 2D grid
  8.     [Tooltip("World Grid Size -  should match UnityEditror snap settings.")]
  9.     [SerializeField] int unityGridSize = 10;
  10.     public int UnityGridSize { get { return unityGridSize; } }
  11.     Dictionary<Vector2Int, Node> grid = new Dictionary<Vector2Int, Node>();
  12.     public Dictionary<Vector2Int, Node> Grid{get {return grid;}}
  13.  
  14.     void Awake() {
  15.         {
  16.             CreateGrid();
  17.         }
  18.     }
  19.  
  20.     public Node GetNode(Vector2Int coordinates)
  21.     {
  22.         if(grid.ContainsKey(coordinates))
  23.         {
  24.             return grid[coordinates];
  25.         }
  26.         return null;
  27.     }
  28.  
  29.     public void BlockNode(Vector2Int coordinates)
  30.     {
  31.         if(grid.ContainsKey(coordinates))
  32.         {
  33.             grid[coordinates].isWalkable = false;
  34.         }
  35.     }
  36.  
  37.     public Vector2Int GetCoordinatesFromPosition(Vector3 position)
  38.     {
  39.         Vector2Int coordinates = new Vector2Int();
  40.         coordinates.x = Mathf.RoundToInt(position.x/ unityGridSize);
  41.         coordinates.y = Mathf.RoundToInt(position.z/ unityGridSize );
  42.  
  43.         return coordinates;
  44.     }
  45.  
  46.     public Vector3 GetPositionFromCoordinates(Vector2Int coordinates)
  47.     {
  48.         Vector3 position = new Vector3();
  49.         position.x = coordinates.x * unityGridSize;
  50.         position.z = coordinates.y * unityGridSize;
  51.  
  52.         return position;
  53.     }
  54.  
  55.     void CreateGrid()
  56.     {
  57.         for(int x = 0; x < gridSize.x; x++)
  58.         {
  59.             for(int y = 0; y < gridSize.y; y++)
  60.             {
  61.                 Vector2Int coordinates = new Vector2Int(x,y);
  62.                 grid.Add(coordinates, new Node(coordinates, true));
  63.                 // Dictionary here; uses a Key and a Description.
  64.                 //the value of coords in vect2Int .info contained in value
  65.                 // The [coordinates] is the key, and .coordinates + .isWalkable is the information/description.
  66.                 // Debug.Log(grid[coordinates].coordinates + " = " + grid[coordinates].isWalkable);
  67.             }
  68.         }
  69.     }
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement