- Home /
Cave generation code broken. Need some help please!
Hi!
Recently I started making a Starbound type game for experience but I ran into a major problem when some code didn't do anything.
Here is the code:
using UnityEngine;
using System.Collections;
public class MapGenerator : MonoBehaviour {
public int width;
public int height;
private enum Cubes
{
Yes,
No
};
private Cubes [,] map;
[Range (0, 100)]
public int fillPercent;
private int tiles;
private int CalculateWalls (int x, int y) {
int neighbors = 0;
for (int x2 = x - 1; x2 < x + 1; x2 ++)
{
for (int y2 = y - 1; y2 < y + 1; y2 ++)
{
if (x2 != -1 && x2 != width && y2 != -1 && y2 != height)
{
if (map [x2, y2] == Cubes.Yes)
{
neighbors ++;
}
}
}
}
return neighbors;
}
void Start () {
CreateMap ();
}
void CreateMap () {
map = new Cubes [width, height];
FillMap ();
}
void FillMap () {
for (int x = 0; x < width; x ++)
{
for (int y = 0; y < height; y ++)
{
int randomizer = Random.Range (0, 9);
if (randomizer == 0)
{
if (tiles / (width * height) * 100 < fillPercent)
{
map [x, y] = Cubes.Yes;
tiles ++;
}
else
{
Debug.Log ("Over fill percentage.");
}
}
else
{
map [x, y] = Cubes.No;
}
}
}
for (int i = 0; i < 5; i ++)
{
SmoothMap ();
}
}
void SmoothMap () {
for (int x = 0; x < width; x ++)
{
for (int y = 0; y < height; y ++)
{
int neighbors = CalculateWalls (x, y);
Debug.Log (neighbors);
if (neighbors > 4)
{
map [x, y] = Cubes.No;
}
}
}
}
void OnDrawGizmos () {
for (int x = 0; x < width; x ++)
{
for (int y = 0; y < height; y ++)
{
Vector2 pos = new Vector2 (x + 0.5f - width / 2, y + 0.5f - height / 2);
if (map != null)
{
if (map [x, y] == Cubes.Yes)
{
Gizmos.color = Color.red;
}
else
{
Gizmos.color = Color.green;
}
Gizmos.DrawCube (pos, Vector3.one);
}
}
}
}
}
I set the fill percent to 75, but it doesn't seem to even consider the fill percentage, and it also freezes (maybe because of a lot of debugging) when adding this line, line 84:
Debug.Log (neighbors);
It doesn't make sense, because it is only called 5 times so I don't understand what's wrong. It is called 5 times because a for loop executes 5 times in a void called in Start, and after that it calls the void Smooth every loop. Doesn't make any sense.
I set the width and height to 100.
I will greatly appreciate any and all help, Cheers!
2 questions for you 1. has this code previously worked? 2. what version of unity are you using?
No the smoothing never worked. Or it never displayed a difference at least. I am using Unity 5.1 the latest.
I was following this http://youtu.be/v7yyZZjF1z4
and wanted to also do the seed system but I couldn't understand a few lines he wrote so I improvised.