- Home /
Cave generation code. At low fill percentage, it seems the upper right is empty
Hello!
I have a code that generates cave. I followed Sebastian Lague's tutorial.
Plug this onto something and set the following variables:
Width = 128 Height = 72 Fill Percent = 50 Seed = null Use Random Seed = true Smoothness = 4 Edge Thickness = 2
using UnityEngine;
using System;
using System.Collections;
public class TerrainGeneration : MonoBehaviour {
public int width, height;
[Range (0, 100)]
public int fillPercent;
private enum Cubes
{
No,
Yes
};
private Cubes [,] map;
public string seed;
public bool useRandomSeed;
public int smoothness;
public int edgeThickness;
int GetNeighbors (int x, int y) {
int neighbors = 0;
for (int x2 = x - 1; x2 < x + 2; x2 ++)
{
for (int y2 = y - 1; y2 < y + 2; y2 ++)
{
if (x2 != x || y2 != y)
{
if (x2 > -1 && x2 < width && y2 > -1 && y2 < height)
{
if (map [x2, y2] == Cubes.Yes)
{
neighbors ++;
}
}
else
{
neighbors ++;
}
}
}
}
return neighbors;
}
void Update () {
if (Input.GetKeyDown (KeyCode.Space))
{
CreateGrid ();
}
}
void CreateGrid () {
map = new Cubes [width, height];
PlaceHoles ();
}
void PlaceHoles () {
if (useRandomSeed == true)
{
seed = Time.time.ToString ();
}
System.Random prng = new System.Random (seed.GetHashCode());
for (int x = 0; x < width; x ++)
{
for (int y = 0; y < height; y ++)
{
if (x < edgeThickness || x > width - edgeThickness - 1 || y < edgeThickness || y > height - edgeThickness - 1)
{
map [x, y] = Cubes.Yes;
}
else if (prng.Next (0, 100) < fillPercent)
{
map [x, y] = Cubes.Yes;
}
}
}
for (int s = 0; s < smoothness; s ++)
{
SmoothMap ();
}
}
void SmoothMap () {
for (int x = 0; x < width; x ++)
{
for (int y = 0; y < height; y ++)
{
int neighbors = GetNeighbors (x, y);
if (neighbors > 4)
{
map [x, y] = Cubes.Yes;
}
else
{
map [x, y] = Cubes.No;
}
}
}
}
void OnDrawGizmos () {
for (int x = 0; x < width; x ++)
{
for (int y = 0; y < height; y ++)
{
if (map != null)
{
if (map [x, y] == Cubes.No)
{
Gizmos.color = Color.green;
}
if (map [x, y] == Cubes.Yes)
{
Gizmos.color = Color.red;
}
Vector3 pos = new Vector3 (x - width / 2 + 0.5f, y - height / 2 + 0.5f, 0);
Gizmos.DrawCube (pos, Vector3.one);
}
}
}
}
}
At 50%, it is clear that it is only developing at the lower left. EDIT
Since my last question I started over, and I have progressed a lot considering it is working. It just looks a little strange that's all. Like it has a seam.
Comment
Your answer
Follow this Question
Related Questions
Cave generation code broken. Need some help please! 0 Answers
Making Cave system in Unity 5 0 Answers
Can I make a cave out of two terrain layers? 1 Answer
How to dig a hole 3 Answers