49 lines
2.3 KiB
C#
49 lines
2.3 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using Object = UnityEngine.Object;
|
|
|
|
namespace Grid {
|
|
public class GridSystem<TGridObject> {
|
|
private readonly TGridObject[,] gridObjectArray;
|
|
|
|
public GridSystem(int width, int height, float cellSize, int floor, float floarHeight, Func<GridSystem<TGridObject>, GridPosition, TGridObject> createGridObject) {
|
|
Width = width;
|
|
Height = height;
|
|
CellSize = cellSize;
|
|
Floor = floor;
|
|
FloorHeight = floarHeight;
|
|
|
|
gridObjectArray = new TGridObject[width, height];
|
|
for (int x = 0; x < width; x++) {
|
|
for (int z = 0; z < height; z++) {
|
|
gridObjectArray[x, z] = createGridObject(this, new(x, z, floor));
|
|
}
|
|
}
|
|
}
|
|
|
|
public int Height { get; }
|
|
public int Width { get; }
|
|
private float CellSize { get; }
|
|
private int Floor { get; }
|
|
private float FloorHeight { get; }
|
|
|
|
public Vector3 GetWorldPosition(GridPosition gridPosition) => new Vector3(gridPosition.XPosition, 0, gridPosition.ZPosition) * CellSize + new Vector3(0, gridPosition.Floor, 0) * FloorHeight;
|
|
|
|
public GridPosition GetGridPosition(Vector3 worldPosition) => new(Mathf.RoundToInt(worldPosition.x / CellSize), Mathf.RoundToInt(worldPosition.z / CellSize), Floor);
|
|
|
|
public void CreateDebugObjects(Transform debugPrefab) {
|
|
for (int x = 0; x < Width; x++) {
|
|
for (int z = 0; z < Height; z++) {
|
|
GridPosition gridPosition = new(x, z, Floor);
|
|
Transform debugTransform = Object.Instantiate(debugPrefab, GetWorldPosition(gridPosition), Quaternion.identity);
|
|
GridDebugObject gridDebugObject = debugTransform.GetComponent<GridDebugObject>();
|
|
gridDebugObject.SetGridObject(GetGridObject(gridPosition));
|
|
}
|
|
}
|
|
}
|
|
|
|
public TGridObject GetGridObject(GridPosition gridPosition) => gridObjectArray[gridPosition.XPosition, gridPosition.ZPosition];
|
|
|
|
public bool IsValidGridPosition(GridPosition gridPosition) => gridPosition is { XPosition: >= 0, ZPosition: >= 0 } && gridPosition.XPosition < Width && gridPosition.ZPosition < Height && gridPosition.Floor == Floor;
|
|
}
|
|
} |