DungeonManager.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using UnityEngine;
  2. namespace Unity.AI.Navigation.Samples
  3. {
  4. /// <summary>
  5. /// Initialize dungeon tiles with a specified width and height
  6. /// </summary>
  7. [DefaultExecutionOrder(-200)]
  8. public class DungeonManager : MonoBehaviour
  9. {
  10. public int m_Width = 10;
  11. public int m_Height = 10;
  12. public float m_Spacing = 4.0f;
  13. public GameObject[] m_Tiles = new GameObject[16];
  14. void Awake()
  15. {
  16. Random.InitState(23431);
  17. var map = new int[m_Width * m_Height];
  18. for (int y = 0; y < m_Height; y++)
  19. {
  20. for (int x = 0; x < m_Width; x++)
  21. {
  22. bool px = false;
  23. bool py = false;
  24. if (x > 0)
  25. px = (map[(x - 1) + y * m_Width] & 1) != 0;
  26. if (y > 0)
  27. py = (map[x + (y - 1) * m_Width] & 2) != 0;
  28. int tile = 0;
  29. if (px)
  30. tile |= 4;
  31. if (py)
  32. tile |= 8;
  33. if (x + 1 < m_Width && Random.value > 0.5f)
  34. tile |= 1;
  35. if (y + 1 < m_Height && Random.value > 0.5f)
  36. tile |= 2;
  37. map[x + y * m_Width] = tile;
  38. }
  39. }
  40. for (int y = 0; y < m_Height; y++)
  41. {
  42. for (int x = 0; x < m_Width; x++)
  43. {
  44. var pos = new Vector3(x * m_Spacing, 0, y * m_Spacing);
  45. if (m_Tiles[map[x + y * m_Width]] != null)
  46. Instantiate(m_Tiles[map[x + y * m_Width]], pos, Quaternion.identity, transform);
  47. }
  48. }
  49. }
  50. }
  51. }