| | |
| | | |
| | | public const int CHUNK_SIZE = 16; // Size of each chunk |
| | | public int LOAD_DISTANCE = 2; // Number of chunks to load around player |
| | | private const int CACHE_CLEAR_DISTANCE = 8; // Distance in chunks before clearing cache (should be > LOAD_DISTANCE) |
| | | private Vector2Int lastCacheClearPosition; // Track position where cache was last cleared |
| | | |
| | | private Dictionary<Vector2Int, bool> loadedChunks = new Dictionary<Vector2Int, bool>(); |
| | | private Dictionary<Vector2Int, TileBase[]> chunkCache = new Dictionary<Vector2Int, TileBase[]>(); |
| | |
| | | { |
| | | StartCoroutine(UpdateLoadedChunks(currentChunk)); |
| | | lastLoadedChunk = currentChunk; |
| | | // Check if we need to clear the cache |
| | | ClearDistantChunks(currentChunk); |
| | | } |
| | | } |
| | | |
| | |
| | | tilemap.SetTile(tilePos, cachedTiles[i]); |
| | | } |
| | | } |
| | | Debug.Log($"Loaded chunk from cache: {chunk}"); |
| | | } |
| | | yield return null; |
| | | } |
| | | private void ClearDistantChunks(Vector2Int currentChunk) |
| | | { |
| | | // If this is the first time, initialize the last clear position |
| | | if (lastCacheClearPosition == default) |
| | | { |
| | | lastCacheClearPosition = currentChunk; |
| | | return; |
| | | } |
| | | |
| | | // Calculate distance moved since last cache clear |
| | | int distanceMoved = Mathf.Max( |
| | | Mathf.Abs(currentChunk.x - lastCacheClearPosition.x), |
| | | Mathf.Abs(currentChunk.y - lastCacheClearPosition.y) |
| | | ); |
| | | |
| | | // If we've moved far enough, clear distant chunks from cache |
| | | if (distanceMoved >= CACHE_CLEAR_DISTANCE) |
| | | { |
| | | List<Vector2Int> chunksToRemove = new List<Vector2Int>(); |
| | | |
| | | foreach (var chunk in chunkCache.Keys) |
| | | { |
| | | int distanceToPlayer = Mathf.Max( |
| | | Mathf.Abs(chunk.x - currentChunk.x), |
| | | Mathf.Abs(chunk.y - currentChunk.y) |
| | | ); |
| | | |
| | | // Remove chunks that are far from current position |
| | | if (distanceToPlayer > LOAD_DISTANCE * 2) |
| | | { |
| | | chunksToRemove.Add(chunk); |
| | | } |
| | | } |
| | | |
| | | // Remove the distant chunks from cache |
| | | foreach (var chunk in chunksToRemove) |
| | | { |
| | | chunkCache.Remove(chunk); |
| | | } |
| | | |
| | | lastCacheClearPosition = currentChunk; |
| | | Debug.Log($"Cleared {chunksToRemove.Count} chunks from cache. Current cache size: {chunkCache.Count}"); |
| | | } |
| | | } |
| | | private IEnumerator GenerateChunk(Vector2Int chunk, List<Vector3Int> destroyedTiles) |
| | | { |
| | | int startX = chunk.x * CHUNK_SIZE; |