99 lines
2.7 KiB
C#
99 lines
2.7 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
namespace DefaultNamespace
|
|
{
|
|
public interface IGridManager
|
|
{
|
|
}
|
|
|
|
public class GridManager : MonoBehaviour, IGridManager
|
|
{
|
|
[SerializeField] private int xCount;
|
|
[SerializeField] private int yCount;
|
|
[SerializeField] public float gridSize;
|
|
[SerializeField] private GameObject pfbGrid;
|
|
[SerializeField] private bool isDrawGrid;
|
|
|
|
private GridCellView[,] _grid;
|
|
|
|
private void Awake()
|
|
{
|
|
CreateGrid();
|
|
}
|
|
|
|
private void CreateGrid()
|
|
{
|
|
var parent = new GameObject("grids");
|
|
_grid = new GridCellView[xCount, yCount];
|
|
for (int x = 0; x < xCount; x++)
|
|
{
|
|
for (int y = 0; y < yCount; y++)
|
|
{
|
|
var gridCell = new GridCell(x, y);
|
|
var go = Instantiate(pfbGrid, parent.transform);
|
|
go.SetActive(true);
|
|
var gridCellView = go.AddComponent<GridCellView>();
|
|
gridCellView.Init(gridCell, gridSize);
|
|
_grid[x, y] = gridCellView;
|
|
}
|
|
}
|
|
}
|
|
|
|
public GridCellView GetCellView(int x, int y)
|
|
{
|
|
if (x < 0 || x >= xCount || y < 0 || y >= yCount)
|
|
return null;
|
|
return _grid[x, y];
|
|
}
|
|
|
|
public bool PutToGrid(int x, int y, GameObject go)
|
|
{
|
|
if (x < 0 || x >= xCount || y < 0 || y >= yCount)
|
|
return false;
|
|
return _grid[x, y].Put(go);
|
|
}
|
|
|
|
public GameObject TakeFromGrid(int x, int y)
|
|
{
|
|
if (x < 0 || x >= xCount || y < 0 || y >= yCount)
|
|
return null;
|
|
return _grid[x, y].Take();
|
|
}
|
|
|
|
public void Check(Vector2 point)
|
|
{
|
|
int x = (int)(point.x / gridSize);
|
|
int y = (int)(point.y / gridSize);
|
|
if (x < 0 || x >= xCount || y < 0 || y >= yCount)
|
|
return;
|
|
|
|
if (!_grid[x, y].IsOccupied)
|
|
{
|
|
_grid[x, y].Put(null);
|
|
}
|
|
else
|
|
{
|
|
_grid[x, y].Take();
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (Input.GetMouseButtonDown(0))
|
|
{
|
|
var screenToWorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
|
|
Check(new Vector2(screenToWorldPoint.x, screenToWorldPoint.z));
|
|
}
|
|
}
|
|
|
|
private void OnDrawGizmos()
|
|
{
|
|
if (!isDrawGrid) return;
|
|
foreach (var gridCellView in _grid)
|
|
{
|
|
gridCellView.DrawGizmos();
|
|
}
|
|
}
|
|
}
|
|
} |