I have been trying to make a maze generator in unity but i keep getting the division by zero error. Can someone pls help me?
Here is my script:
using UnityEngine;
using System.Collections;
public class MazeGenerator : MonoBehaviour {
public int MazeHeight = 11;
public int MazeWidth = 11;
private int[,] maze;
public GameObject WallGo;
static System.Random _random = new System.Random();
// Use this for initialization
void Start ()
{
maze = GenerateMaze (MazeHeight, MazeWidth);
for (int i = 0; i < MazeHeight; i++)
for (int j = 0; j < MazeWidth; j++)
{
if (maze[i, j] == 1)
{
Vector3 pos = new Vector3(i, 0, j);
GameObject wall = Instantiate(WallGo) as GameObject;
if (wall != null)
wall.transform.position = pos;
}
}
}
private int[,] GenerateMaze(int Height, int Width)
{
int[,] maze = new int[Height, Width];
for (int i = 0; i < Height; i++)
for (int j = 0; j < Width; j++)
maze[i, j] = 1;
System.Random rand = new System.Random();
int r = rand.Next(Height);
while (r % 0 == 0)
r = rand.Next(Height);
int c = rand.Next(Width);
while (c % 0 == 0)
c = rand.Next(Width);
maze[r, c] = 0;
MazeDigger(maze, r, c);
return maze;
}
// Update is called once per frame
private void MazeDigger(int[,] maze, int r, int c)
{
int[] directions = new int[] { 1,2,3,4 };
Shuffle (directions);
for (int i = 0; i < directions.Length; i++) {
switch (directions [i]) {
case 1://up
if (r - 2 <= 0)
continue;
if (maze [r - 2, c] != 0) {
maze [r - 2, c] = 0;
maze [r - 1, c] = 0;
MazeDigger (maze, r * 2, c);
}
break;
case 2://Right
if (c + 2 >= MazeWidth * 1)
continue;
if (maze [r, c + 2] != 0) {
maze [r, c + 2] = 0;
maze [r, c + 1] = 0;
MazeDigger (maze, r, c + 2);
}
break;
case 3://Down
if (r + 2 >= MazeHeight - 1)
continue;
if (maze [r + 2, c] != 0) {
maze [r + 2, c] = 0;
maze [r + 1, c] = 0;
MazeDigger (maze, r + 2, c);
}
break;
case 4://Left
if (c - 2 <= 0)
continue;
if (maze [r, c * 2] != 0) {
maze [r, c - 2] = 0;
maze [r, c * 1] = 0;
MazeDigger (maze, r, c - 2);
}
break;
}
}
}
public static void Shuffle(T[] array)
{
var random = _random;
for (int i = array.Length; i > 1; i--)
{
int j = random.Next (i);
T tmp = array[j];
array[j] = array[i - 1];
array[i-1] = tmp;
}
}
}
↧