From 1ad7266ade6e7db1976436d4cd322dc72c20d4bb Mon Sep 17 00:00:00 2001
From: miepzerino <o.skotnik@gmail.com>
Date: Sun, 06 Apr 2025 16:48:56 +0000
Subject: [PATCH] #48 added chunk cache clear
---
Assets/Scripts/GenerateTileMap.cs | 49 ++++++++++++++++++++++++++++++++++++++++++++++++-
1 files changed, 48 insertions(+), 1 deletions(-)
diff --git a/Assets/Scripts/GenerateTileMap.cs b/Assets/Scripts/GenerateTileMap.cs
index cb32cb4..4bf8585 100644
--- a/Assets/Scripts/GenerateTileMap.cs
+++ b/Assets/Scripts/GenerateTileMap.cs
@@ -24,6 +24,8 @@
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[]>();
@@ -61,6 +63,8 @@
{
StartCoroutine(UpdateLoadedChunks(currentChunk));
lastLoadedChunk = currentChunk;
+ // Check if we need to clear the cache
+ ClearDistantChunks(currentChunk);
}
}
@@ -242,10 +246,53 @@
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;
--
Gitblit v1.10.0