84 lines
2.5 KiB
C#
84 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Tilemaps;
|
|
|
|
public class GridManager : MonoBehaviour
|
|
{
|
|
#region Statication
|
|
|
|
public static GridManager instance;
|
|
|
|
private void Awake()
|
|
{
|
|
if (instance != null && instance != this)
|
|
{
|
|
Destroy(gameObject);
|
|
return;
|
|
}
|
|
instance = this;
|
|
}
|
|
|
|
#endregion
|
|
[SerializeField] private int width;
|
|
[SerializeField] private int height;
|
|
|
|
[SerializeField] private TileObject tilePrefab;
|
|
|
|
[SerializeField] Camera cam;
|
|
|
|
private Dictionary<Vector2, TileObject> allTiles = new();
|
|
private void Start()
|
|
{
|
|
GenerateGrid();
|
|
cam.transform.position = new Vector3((float)width / 2, (float)height / 2, 0);
|
|
foreach (PlayerEntity player in TurnHandler.instance.playerEntities)
|
|
{
|
|
player.currentTile = GetTile(player.transform.position);
|
|
}
|
|
foreach (Enemy enemy in TurnHandler.instance.enemyEntities)
|
|
{
|
|
enemy.currentTile = GetTile(enemy.transform.position);
|
|
}
|
|
}
|
|
|
|
private void GenerateGrid()
|
|
{
|
|
for (int x = 0; x < width; x++)
|
|
{
|
|
for (int y = 0; y < height; y++)
|
|
{
|
|
Vector2 pos = new Vector2(x - ((float)width / 2) + 0.5f, y - ((float)height / 2) + 0.5f);
|
|
TileObject newTile = Instantiate(tilePrefab, pos, Quaternion.identity);
|
|
newTile.name = $"Tile {x} {y}";
|
|
allTiles[pos] = newTile;
|
|
}
|
|
}
|
|
GetTileNeighbors();
|
|
}
|
|
|
|
private void GetTileNeighbors()
|
|
{
|
|
for (int x = 0; x < width; x++)
|
|
{
|
|
for (int y = 0; y < height; y++)
|
|
{
|
|
Vector2 pos = new Vector2(x - ((float)width / 2) + 0.5f, y - ((float)height / 2) + 0.5f);
|
|
TileObject currentTile = allTiles[pos];
|
|
if (GetTile(pos + Vector2.up)) { currentTile.neighbors.Add(GetTile(pos+Vector2.up));}
|
|
if (GetTile(pos + Vector2.down)) { currentTile.neighbors.Add(GetTile(pos+Vector2.down));}
|
|
if (GetTile(pos + Vector2.left)) { currentTile.neighbors.Add(GetTile(pos+Vector2.left));}
|
|
if (GetTile(pos + Vector2.right)) { currentTile.neighbors.Add(GetTile(pos+Vector2.right));}
|
|
}
|
|
}
|
|
}
|
|
|
|
public TileObject GetTile(Vector2 pos)
|
|
{
|
|
if (allTiles.TryGetValue(pos, out TileObject tile))
|
|
{
|
|
return tile;
|
|
}
|
|
return null;
|
|
}
|
|
}
|