unity 使用深度优先搜索生成迷宫之二
之前写过一篇使用深度优先搜索生成随机迷宫的文章
https://www.cnblogs.com/JinT-Hwang/p/9599913.html
今天做了一下优化,使用unity的TileMap来做,并且代码减少到100行以内。
先看一下效果图

下面直接是代码,至于在unity中怎么创建tilemap资源这里就不讲了:
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4using UnityEngine.Tilemaps; 5 6public class TileMapTestBehaviour : MonoBehaviour 7{ 8 public TileBase baseTile; 9 public Tilemap tilemap; 10 11 public int mapWidth; 12 public int mapHeight; 13 14 public float tileSize = 0.16f; 15 16 private Stack<Vector3Int> tileMapPosStack; 17 private List<Vector3Int> tileSaveList; 18 private Queue<Vector3Int> recordQueue; 19 20 private static readonly List<Vector3Int> tilesOffset = new List<Vector3Int>() 21 { 22 Vector3Int.down,Vector3Int.right,Vector3Int.up,Vector3Int.left 23 }; 24 25 // Use this for initialization 26 void Start() 27 { 28 tileMapPosStack = new Stack<Vector3Int>(); 29 tileSaveList = new List<Vector3Int>(); 30 recordQueue = new Queue<Vector3Int>(); 31 32 tileMapPosStack.Push(Vector3Int.zero); 33 tileSaveList.Add(Vector3Int.zero); 34 35 CreateMap_DFS(); 36 } 37 38 private void CreateMap_DFS() 39 { 40 Vector3Int currentTile; 41 Vector3Int nextTile; 42 43 List<Vector3Int> aroundTileList = new List<Vector3Int>(); 44 45 while (tileMapPosStack.Count > 0) 46 { 47 currentTile = tileMapPosStack.Pop(); 48 49 for (int i = 0; i < 4; i++) 50 { 51 nextTile = currentTile + tilesOffset[i]; 52 53 if (!tileSaveList.Contains(nextTile)) 54 { 55 aroundTileList.Add(nextTile); 56 } 57 } 58 59 if (aroundTileList.Count >= 3) 60 { 61 while (aroundTileList.Count > 0) 62 { 63 Vector3Int tilePos = aroundTileList[Random.Range(0, aroundTileList.Count)]; 64 aroundTileList.Remove(tilePos); 65 66 if (IsTileInRange(tilePos)) 67 { 68 tileMapPosStack.Push(tilePos); 69 } 70 } 71 72 if (!tileSaveList.Contains(currentTile)) 73 tileSaveList.Add(currentTile); 74 75 recordQueue.Enqueue(currentTile); 76 } 77 78 aroundTileList.Clear(); 79 } 80 81 StartCoroutine("Display"); 82 } 83 84 private bool IsTileInRange(Vector3Int tilePos) 85 { 86 return tilePos.x >= 0 && tilePos.x < mapWidth && tilePos.y >= 0 && tilePos.y < mapHeight; 87 } 88 89 private IEnumerator Display() 90 { 91 while (recordQueue.Count > 0) 92 { 93 yield return new WaitForSecondsRealtime(0.1f); 94 95 tilemap.SetTile(recordQueue.Dequeue(), baseTile); 96 } 97 } 98}
欢迎交流,转载注明出处。:)