Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class Maze : MonoBehaviour
- {
- public int Total_Width = 100;
- public int Total_Height = 100;
- public Vector3 Origin = Vector3.zero;
- public GameObject Wall;
- public GameObject BorderWall;
- private enum Direction
- {
- HORIZONTAL,
- VERTICAL
- }
- //Returns direction depending if width or height are larger
- Direction getDirection(int width, int height)
- {
- if (width == height)
- {
- int x = Random.Range(0, 2);
- if (x == 0)
- return Direction.VERTICAL;
- else
- return Direction.HORIZONTAL;
- }
- return (width > height ? Direction.VERTICAL : Direction.HORIZONTAL);
- }
- //Only for graphic effect
- void AddBorder()
- {
- for (int i = 0; i < Total_Width; i++)
- {
- for (int j = 0; j < Total_Height; j++)
- {
- if (i == Total_Width - 1 || j == Total_Height - 1 || i == 0 || j == 0)
- Instantiate(BorderWall, new Vector3(i, 0, j), Quaternion.identity);
- }
- }
- }
- void Start()
- {
- AddBorder();
- Divide(0, 0, Total_Width, Total_Height, getDirection(Total_Width, Total_Height), 0);
- }
- void HandleVertical(int x, int y, int width, int height, Direction d, int index)
- {
- int NextPos = Random.Range(x + 1, x + width - 1); // Random place to "add wall"
- int Hole = Random.Range(y + 1, y + height - 1); // Making 1 block space in that wall
- for (int i = y + 1; i < (y + height - 1); i++)
- {
- if (i != Hole)
- {
- Instantiate(Wall, new Vector3(i, 0, NextPos), Quaternion.identity); // Create wall block
- }
- }
- Divide(x, y, NextPos - x, height, d, index);
- Divide(NextPos, y, x + width - NextPos, height, d, index);
- }
- void HandleHorizontal(int x, int y, int width, int height, Direction d, int index)
- {
- int NextPos = Random.Range(y + 1, y + height - 1); // Random place to "add wall"
- int Hole = Random.Range(x + 1, x + width - 1); // Making 1 block space in that wall
- for (int i = x + 1; i < (x + width - 1); i++)
- {
- if (i != Hole)
- {
- Instantiate(Wall, new Vector3(NextPos, 0, i), Quaternion.identity); // Create wall block
- }
- }
- Divide(x, y, width, NextPos - y, d, index);
- Divide(x, NextPos, width, y + height - NextPos, d, index);
- }
- // Main recursive function
- void Divide(int x, int y, int width, int height, Direction dir, int index)
- {
- Direction d = getDirection(width, height);
- index++;
- if (index > 20)
- {
- Debug.Log("Stack Overflow Warning");
- return;
- }
- if (width <= 1 || height <= 1) // Room size
- {
- return;
- }
- if (d == Direction.VERTICAL)
- {
- HandleVertical(x, y, width, height, d, index);
- }
- else if (d == Direction.HORIZONTAL)
- {
- HandleHorizontal(x, y, width, height, d, index);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement