using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
//Make this into a constructor because using monobehavior doesnt allow constructors and you need a constructor for parameters of the grid system
public class GridSystem<TGridObject>
{
//A constructor is like a function with no return type. The name of Constructor is the same as the class name
private int width;
private int height;
private float cellSize;
//this is creating a 2d array because the coma makes an x and y
private TGridObject[,] gridObjectArray;
public GridSystem(int width, int height, float cellSize, Func<GridSystem<TGridObject>, GridPosition, TGridObject> createGridObject)
{
this.width = width;
this.height = height;
this.cellSize = cellSize;
//creating the 2d grid array parameters
gridObjectArray = new TGridObject[width, height];
for (int x = 0; x < width; x++)
{
for (int z = 0; z < height; z++)
{
//This creates gridObjects
GridPosition gridPosition = new GridPosition(x, z);
gridObjectArray[x, z] = createGridObject(this, gridPosition);
}
}
}
public Vector3 GetWorldPosition(GridPosition gridPosition)
{
return new Vector3(gridPosition.x, 0, gridPosition.z) * cellSize;
}
public GridPosition GetGridPostion(Vector3 worldPositiom)
{
return new GridPosition
(
Mathf.RoundToInt(worldPositiom.x / cellSize),
Mathf.RoundToInt(worldPositiom.z / cellSize)
);
}
public void CreateDebugObjects(Transform gridDebugObjectPrefab)
{
for (int x = 0; x < width; x++)
{
for (int z = 0; z < height; z++)
{
GridPosition gridPosition = new GridPosition(x, z);
Transform debugTransform = GameObject.Instantiate(gridDebugObjectPrefab, GetWorldPosition(gridPosition), Quaternion.identity);
GridDebugObject gridDebugObject = debugTransform.GetComponent<GridDebugObject>();
gridDebugObject.SetGridOjbect(GetGridObject(gridPosition));
}
}
}
public TGridObject GetGridObject(GridPosition gridPosition)
{
return gridObjectArray[gridPosition.x, gridPosition.z];
}
//This is setting up boundraies for the unit
public bool IsValidGridPosition(GridPosition gridPosition)
{
return gridPosition.x >= 0 &&
gridPosition.z >= 0 &&
gridPosition.x < width &&
gridPosition.z < height;
}
//exposing the width and height
public int GetWidth()
{
return width;
}
public int GetHeight()
{
return height;
}
}