using HPJ.Presentation.Agents; using HPJ.Simulation; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace HPJ.Presentation { [RequireComponent(typeof(NavigationAgent))] public class AgentAreaDisplay : MonoBehaviour { [SerializeField] private AreaDisplayTile _tilePrefab; private Transform TileSpawn; [SerializeField] private bool _showTilesOutOfReach = true; [SerializeField] private int _range = 25; [SerializeField] private float _updatePeriod = 1; private float _updateTime = 0; private List _activeTiles = new List(); private List _pool = new List(); private NavigationAgent _agent; private void Awake() { TileSpawn = new GameObject($"Tile Spawn for {name}").transform; _agent = GetComponent(); _updateTime = _updatePeriod + 1; } // Update is called once per frame void Update() { if (NavigationManager.Instance == null) { return; } if (!NavigationManager.Instance) { return; } if (NavigationManager.Instance.MapSets.Count <= 0) { return; } _updateTime += Time.deltaTime; if (_updateTime >= _updatePeriod) { _updateTime = 0; UpdateTiles(); } } public void UpdateTiles() { //Debug.Log("Update Tiles"); ReturnAllTiles(); List TilesInRangeBySteps = _agent.GetTraversableTilesInRangeBySteps(_range); if (TilesInRangeBySteps.Count == 0 && _updatePeriod > 1) { Invoke(nameof(UpdateTiles), 0.1f); return; } if (_showTilesOutOfReach) { List TilesInRange = _agent.GetTraversableTilesInRange(_range); foreach (IntVector2 Tile in TilesInRange) { AreaDisplayTile NewTile = GetTile(); NewTile.Set(_agent.CurrentMap, Tile, TilesInRangeBySteps.Contains(Tile)); } } else { foreach (IntVector2 Tile in TilesInRangeBySteps) { AreaDisplayTile NewTile = GetTile(); NewTile.Set(_agent.CurrentMap, Tile, true); } } } protected AreaDisplayTile GetTile() { if (_pool.Count > 0) { AreaDisplayTile NewTile = _pool[0]; _pool.RemoveAt(0); NewTile.gameObject.SetActive(true); _activeTiles.Add(NewTile); return NewTile; } else { AreaDisplayTile NewTile = Instantiate(_tilePrefab, TileSpawn); NewTile.Initialize(_agent.CurrentMap.SetSettings.MapSettings.TileSize); _activeTiles.Add(NewTile); return NewTile; } } protected void ReturnTile(AreaDisplayTile Tile) { Tile.gameObject.SetActive(false); _pool.Add(Tile); _activeTiles.Remove(Tile); } protected void ReturnAllTiles() { foreach(AreaDisplayTile Tile in _activeTiles) { Tile.gameObject.SetActive(false); _pool.Add(Tile); } _activeTiles.Clear(); } } }