59 lines
1.5 KiB
C#
59 lines
1.5 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
[ExecuteInEditMode]
|
|
public class GridHandler : MonoBehaviour
|
|
{
|
|
[Tooltip("How large (in meters) one grid block side is")]
|
|
public float gridSize = 10f;
|
|
|
|
[Tooltip("The player's transform to track")]
|
|
public Transform playerTransform;
|
|
|
|
private Vector3Int lastPlayerGrid = new Vector3Int(-99999, -99999, -99999);
|
|
|
|
public event Action<Vector3Int> onPlayerGridChange;
|
|
|
|
private void Update()
|
|
{
|
|
if (playerTransform == null)
|
|
{
|
|
Debug.LogWarning("Grid Handler Has No Player Transform!");
|
|
return;
|
|
}
|
|
Vector3 position = playerTransform.position;
|
|
Vector3Int vector3Int = new Vector3Int(Mathf.FloorToInt(position.x / gridSize), Mathf.FloorToInt(position.y / gridSize), Mathf.FloorToInt(position.z / gridSize));
|
|
if (vector3Int != lastPlayerGrid)
|
|
{
|
|
if (this.onPlayerGridChange != null)
|
|
{
|
|
this.onPlayerGridChange(vector3Int);
|
|
}
|
|
lastPlayerGrid = vector3Int;
|
|
}
|
|
}
|
|
|
|
public Vector3 GetGridCenter(Vector3Int grid)
|
|
{
|
|
float num = gridSize * 0.5f;
|
|
return new Vector3((float)grid.x * gridSize + num, (float)grid.y * gridSize + num, (float)grid.z * gridSize + num);
|
|
}
|
|
|
|
private void OnDrawGizmos()
|
|
{
|
|
for (int i = -1; i <= 1; i++)
|
|
{
|
|
for (int j = -1; j <= 1; j++)
|
|
{
|
|
for (int k = -1; k <= 1; k++)
|
|
{
|
|
bool flag = i == 0 && j == 0 && k == 0;
|
|
Vector3 gridCenter = GetGridCenter(lastPlayerGrid + new Vector3Int(i, j, k));
|
|
Gizmos.color = (flag ? Color.green : Color.red);
|
|
Gizmos.DrawWireCube(gridCenter, Vector3.one * (gridSize * (flag ? 0.95f : 1f)));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|