Guest User

Procedural Dungeon 2D

a guest
Jun 14th, 2022
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.78 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Text.RegularExpressions;
  4. using UnityEngine;
  5. using UnityEngine.SceneManagement;
  6. using UnityEditor;
  7.  
  8.  
  9. public class LevelGenerator : MonoBehaviour
  10. {
  11.  
  12.     public GameObject layoutRoom;       // The room prefab to generate.
  13.     public Color startColor, endColor;  // Colors for the start and end rooms.
  14.     public int distanceToEnd;           // Number of rooms generated.
  15.     public Transform generatorPoint;    // The distance between rooms.
  16.  
  17.     public enum Direction { up, right, down, left };
  18.     public Direction selectedDirection;
  19.  
  20.     // Dimensions of each room - based off of camera size.
  21.     public float xOffset = 18f, yOffset = 10f;                                                                                                            
  22.  
  23.     public LayerMask whatIsRoom;
  24.  
  25.     //private Vector2Int startCoords = Vector2Int.zero, endCoords;
  26.  
  27.     [SerializeField]
  28.     private List<GameObject> layoutRoomObjects = new List<GameObject>();
  29.     //[SerializeField]
  30.     //private List<Vector2Int> roomCoords = new List<Vector2Int>();
  31.    
  32.     public enum RoomVariations { SingleN, SingleE, SingleS, SingleW, DoubleNE, DoubleSE, DoubleSW, DoubleNW, DoubleNS, DoubleEW, TripleN, TripleE, TripleS, TripleW, Intersection };
  33.     public RoomVariations variation;
  34.  
  35.     Direction entrance;
  36.  
  37.     // Start is called before the first frame update
  38.     void Start()
  39.     {
  40.         //Decide upon direction of dungeon entrance in the start room.
  41.         entrance = (Direction)Random.Range(0, 4);
  42.  
  43.         // Generates the map.
  44.         for (int i = 0; i < distanceToEnd; i++)
  45.         {
  46.             GameObject newRoom = Instantiate(layoutRoom, generatorPoint.position, generatorPoint.rotation);     // Generates a new room.
  47.             newRoom.name = GenerateRoomName(newRoom);   // Names the room based on an x,y coordinate system.
  48.             layoutRoomObjects.Add(newRoom);     // Add the room to the room database.
  49.  
  50.             // Tagging of start and end rooms.
  51.             if (i == 0)
  52.             {
  53.                 newRoom.GetComponent<SpriteRenderer>().color = startColor;
  54.                 //doorways.AssignCoords(0, 0);
  55.             }
  56.             else if (i + 1 == distanceToEnd)
  57.                 newRoom.GetComponent<SpriteRenderer>().color = endColor;
  58.            
  59.             Vector3 lastPos;
  60.  
  61.             while (Physics2D.OverlapCircle(generatorPoint.position, .2f, whatIsRoom))
  62.             {
  63.                 lastPos = generatorPoint.position;
  64.                 // Pick a random direction to create the next room.
  65.                 selectedDirection = AssignNextDirection(newRoom);
  66.                 MoveGenerationPoint();
  67.                 if (Physics2D.OverlapCircle(generatorPoint.position, .2f, whatIsRoom))
  68.                     generatorPoint.position = lastPos;
  69.             }
  70.                
  71.         }
  72.  
  73.     }
  74.  
  75.     // Update is called once per frame
  76.     void Update()
  77.     {
  78.         if (Input.GetKeyDown(KeyCode.Space))
  79.         {
  80.             SceneManager.LoadScene("Test");
  81.         }
  82.     }
  83.  
  84.     // Method for determining what direction to spawn the next room.
  85.     public void MoveGenerationPoint()
  86.     {
  87.  
  88.         Vector3[] dir = new[] { new Vector3(0f, yOffset, 0f), new Vector3(xOffset, 0f, 0f), new Vector3(0f, -yOffset, 0f), new Vector3(-xOffset, 0f, 0f) };
  89.  
  90.         for (int i = 0; i < 4; i++)
  91.             if (selectedDirection == (Direction)i)
  92.                 generatorPoint.position += dir[(int)selectedDirection];
  93.  
  94.     }
  95.  
  96.     private string GenerateRoomName(GameObject _room)
  97.     {
  98.         int _x, _y;
  99.  
  100.         if (_room.transform.position.x != 0)
  101.             _x = (int)(_room.transform.position.x / xOffset);
  102.         else _x = 0;
  103.  
  104.         if (_room.transform.position.y != 0)
  105.             _y = (int)(_room.transform.position.y / yOffset);
  106.         else _y = 0;
  107.  
  108.         return string.Format("Room {0}, {1}", _x, _y);
  109.     }
  110.  
  111.     private Vector2Int GetCoords(GameObject _room)
  112.     {
  113.         string _name = _room.name;
  114.        
  115.         string[] _coords = Regex.Split(_name, @"\D+");
  116.  
  117.         // _coords[0] is "" for some reason.
  118.         int _x = int.Parse(_coords[1]),
  119.             _y = int.Parse(_coords[2]);
  120.  
  121.         return new Vector2Int(_x, _y);
  122.     }
  123.  
  124.     private Direction AssignNextDirection(GameObject _room)
  125.     {
  126.         Direction _next = 0;             // Ultimately this will be the direction for the next generated room.
  127.         bool _rerollDirection = false;       // This determines whether or not the generator is trying to generate past the entrance direction.
  128.         Vector2Int _coords = GetCoords(_room);
  129.         /* How this works:
  130.          * If the dungeon entrance is placed at the top of the room, that means no room y-coords should positively exceed 0.
  131.          * Vice Versa applies: If the enrances is at the bottom, then no room y-coords should negatively exceed 0.
  132.          * The same rules applies for x-coords regarding eastern and western dungeon entrances.
  133.          */
  134.        
  135.         while (!_rerollDirection)
  136.         {
  137.             _next = (Direction)Random.Range(0, 4);
  138.             print(_next);
  139.             switch (entrance)
  140.             {
  141.                 case Direction.up:
  142.                     if (_coords.y + 1 > 0 && _next == Direction.up)
  143.                     {
  144.                         _rerollDirection = false;
  145.                         //print(_coords + " wrong turn going up!");
  146.                     }
  147.                     else
  148.                         _rerollDirection = true;
  149.                     break;
  150.                 case Direction.right:
  151.                     if (_coords.x + 1 > 0 && _next == Direction.right)
  152.                     {
  153.                         _rerollDirection = false;
  154.                         //print(_coords + " wrong turn going right!");
  155.                     }
  156.                     else
  157.                         _rerollDirection = true;
  158.                     break;
  159.                 case Direction.down:
  160.                     if (_coords.y - 1 < 0 && _next == Direction.down)
  161.                     {
  162.                         _rerollDirection = false;
  163.                         //print(_coords + " wrong turn going down!");
  164.                     }
  165.                     else
  166.                         _rerollDirection = true;
  167.                     break;
  168.                 case Direction.left:
  169.                     if (_coords.x - 1 < 0 && _next == Direction.left)
  170.                     {
  171.                         _rerollDirection = false;
  172.                         //print(_coords + " wrong turn going left!");
  173.                     }
  174.                     else
  175.                         _rerollDirection = true;
  176.                     break;
  177.             }
  178.         }
  179.         //print("Next room will be at " + _next + " from " + _coords);
  180.         return _next;
  181.     }
  182.  
  183. }
  184.    
  185.  
Advertisement
Add Comment
Please, Sign In to add comment