- Home /
2d Procedural terrain generation forest
Hi, I am currently working on a project where I want procedural world generation. My main problem is, how to spawn my trees on top of my grass blocks, because everything I tried becomes always weird like this;
Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Worldgeneration : MonoBehaviour
{
[SerializeField] int width, height;
[SerializeField] int minStoneheight, maxStoneHeight;
[SerializeField] GameObject dirt, grass, stone, tree;
public Transform player;
public int spawnPointX;
public int spawnPointY;
public int maxtreespawn = 0;
public void Awake()
{
spawnPointX = Random.Range(0, 300); // for my playerspawn
spawnPointY = Random.Range(70, 90); // for my playerspawn
}
void Start()
{
Generation();
Vector3 spawnPosition = new Vector3(spawnPointX, spawnPointY, 0);
player.transform.position = spawnPosition;
}
void Update()
{
}
void Generation()
{
for (int x = 0; x < width; x++) //This will help spawn a tile on the x axis
{
// procedural generation increase and decrease the height value and apply this to the
// stonespawndistance
int minHeight = height - 1;
int maxHeight = height + 2;
height = Random.Range(minHeight, maxHeight);
int minStoneSpawnDistance = height - minStoneheight;
int maxStoneSpawnDistance = height - maxStoneHeight;
int totalStoneSpawnDistance = Random.Range(minStoneSpawnDistance, maxStoneSpawnDistance);
for (int y = 0; y < height; y++)//This will help spawn a tile on the y axis
{
if (y < totalStoneSpawnDistance)
{
spawnObj(stone, x, y);
}
else
{
spawnObj(dirt, x, y);
}
if (totalStoneSpawnDistance == height)
{
spawnObj(stone, x, height);
}
else
{
spawnObj(grass, x, height);
}
if(maxtreespawn < 50)
{
spawnObj(tree, Random.Range(0, width), height + 2);
maxtreespawn++;
}
}
}
}
void spawnObj(GameObject obj, int width, int height)//What ever we spawn will be a child of our procedural generation gameObj
{
obj = Instantiate(obj, new Vector2(width, height), Quaternion.identity);
obj.transform.parent = this.transform;
}
}

Comment
Your answer
Follow this Question
Related Questions
How can I use 2D sprites for characters in a game with 3D collision? 0 Answers
Game Resolution and Scaling Unity 2D 0 Answers
Are there any plans to manipulate SpriteRenderer.SortOrder from Mecanim Animation? 0 Answers
Isometric 2D images mixed with 3D objects ? 0 Answers
How to make a 2D Character react to In-game A.I (Objects)? 0 Answers