Infinite Top Down 2D Procedurally Generated Terrain (Help)
When using procedurally generated terrain No matter whether I am working with 2D sprites or 3D cubes I always find myself at this same point in development that I can never get past. I'm talking about the infinite terrain part, I can make say a 360x360 square of sprites colouring them using Perlin noise just fine, but when it comes to having chunks and that I just don't know where to start. I don't know how difficult this task is but if it relatively easy I would greatly appreciate if you altered my code to make this work, but if it is too difficult or time consuming I totally get it. I am semi-new to unity and c# (so you may have to elaborate on some things for me)
Thanks,
Here is my code:
public class Generation : MonoBehaviour {
public float TextureResolution;
private float TileSpacing;
public GameObject TilePrefab;
public GameObject World;
public Sprite Sand;
public Sprite Stone;
public Sprite Snow;
public Sprite Grass;
public Sprite Dirt;
private GameObject C;
private float maxX = 320;
private float maxY = 320;
private int seed;
void Start()
{
TileSpacing = TextureResolution / 100;
Regenerate();
}
void Update()
{
if (Input.GetKeyDown (KeyCode.Mouse0))
{
var children = new List<GameObject>();
foreach (Transform child in transform) children.Add(child.gameObject);
children.ForEach(child => Destroy(child));
Regenerate ();
}
}
private void Regenerate(){
seed = Random.Range (50, 300);
float width = TilePrefab.transform.lossyScale.x * TileSpacing;
float height = TilePrefab.transform.lossyScale.y * TileSpacing;
for (float i = 0; i < maxX; i++)
{
for (float k = 0; k < maxY; k++)
{
var perlin = Mathf.PerlinNoise(i / seed, k / seed);
if (perlin >= 0)
{
C = (GameObject)Instantiate(TilePrefab, new Vector3(i * width, k * height, 2), Quaternion.identity,this.transform);
SpriteRenderer Sr1 = C.GetComponent<SpriteRenderer>();
if (perlin <= 0.2)
{
Sr1.sprite = Stone;
Sr1.color = new Color(perlin*2,perlin*2,perlin*2);
}
else if (perlin <= 0.3)
{
Sr1.sprite = Grass;
Sr1.color = new Color(perlin*2,perlin*2,perlin*2);
}
else if (perlin <= 0.7)
{
Sr1.sprite = Grass;
Sr1.color = new Color(perlin*2,perlin*2,perlin*2);
}
else if (perlin <= 0.75)
{
Sr1.sprite = Sand;
Sr1.color = new Color(perlin*2,perlin*2,perlin*2);
}
else if (perlin <= 1)
{
Sr1.color = new Color(0,perlin,1);
}
}
}
}
}
}
Your answer
Follow this Question
Related Questions
Is there any way to trigger a popUp UI when a player steps in a specific set of tiles? 0 Answers
top down 2d game, aim weapon with mouse. please help 1 Answer
How do I make it so that two player controlled objects of varying speeds stay close to each other? 0 Answers
New user question about 2D top down game and collision. 0 Answers