之前写过一篇使用深度优先搜索生成随机迷宫的文章
https://www.cnblogs.com/JinT-Hwang/p/9599913.html
今天做了一下优化,使用unity的TileMap来做,并且代码减少到100行以内。
先看一下效果图
下面直接是代码,至于在unity中怎么创建tilemap资源这里就不讲了:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; public class TileMapTestBehaviour : MonoBehaviour { public TileBase baseTile; public Tilemap tilemap; public int mapWidth; public int mapHeight; public float tileSize = 0.16f; private Stack<Vector3Int> tileMapPosStack; private List<Vector3Int> tileSaveList; private Queue<Vector3Int> recordQueue; private static readonly List<Vector3Int> tilesOffset = new List<Vector3Int>() { Vector3Int.down,Vector3Int.right,Vector3Int.up,Vector3Int.left }; // Use this for initialization void Start() { tileMapPosStack = new Stack<Vector3Int>(); tileSaveList = new List<Vector3Int>(); recordQueue = new Queue<Vector3Int>(); tileMapPosStack.Push(Vector3Int.zero); tileSaveList.Add(Vector3Int.zero); CreateMap_DFS(); } private void CreateMap_DFS() { Vector3Int currentTile; Vector3Int nextTile; List<Vector3Int> aroundTileList = new List<Vector3Int>(); while (tileMapPosStack.Count > 0) { currentTile = tileMapPosStack.Pop(); for (int i = 0; i < 4; i++) { nextTile = currentTile + tilesOffset[i]; if (!tileSaveList.Contains(nextTile)) { aroundTileList.Add(nextTile); } } if (aroundTileList.Count >= 3) { while (aroundTileList.Count > 0) { Vector3Int tilePos = aroundTileList[Random.Range(0, aroundTileList.Count)]; aroundTileList.Remove(tilePos); if (IsTileInRange(tilePos)) { tileMapPosStack.Push(tilePos); } } if (!tileSaveList.Contains(currentTile)) tileSaveList.Add(currentTile); recordQueue.Enqueue(currentTile); } aroundTileList.Clear(); } StartCoroutine("Display"); } private bool IsTileInRange(Vector3Int tilePos) { return tilePos.x >= 0 && tilePos.x < mapWidth && tilePos.y >= 0 && tilePos.y < mapHeight; } private IEnumerator Display() { while (recordQueue.Count > 0) { yield return new WaitForSecondsRealtime(0.1f); tilemap.SetTile(recordQueue.Dequeue(), baseTile); } } }
欢迎交流,转载注明出处。:)
原文地址:https://www.cnblogs.com/JinT-Hwang/p/10027922.html
时间: 2024-10-11 05:25:19