- Home /
Question by
Winj42 · Jan 14, 2018 at 02:42 PM ·
c#terraintreesterrain gen
Instantiated Objects not Following Perlin Noise
I'm trying to make a procedurally generated landscape, and I got the Perlin Noise generation part down, but when I try to randomly instantiate trees, they're all at the same height. I used the code from a video to make my terrain, but I added the tree part. Here's my code:
using UnityEngine; using System.Collections;
public class ProcGen : MonoBehaviour {
public int depth = 20;
public float scale = 20f;
public int width = 512;
public int height = 512;
public int seed;
public GameObject tree;
public int treeNumber;
void Start()
{
if (seed == 0)
{
seed = Random.Range (1, 10000);
}
Terrain terrain = GetComponent<Terrain> ();
terrain.terrainData = GenerateTerrain(terrain.terrainData);
int randX = Random.Range(0, width);
int randZ = Random.Range(0, height);
float terrainHeight = CalculateHeight(randX, randZ);
for (int f = 0; f < treeNumber; f++)
{
randX = Random.Range(0, width);
randZ = Random.Range(0, height);
terrainHeight = CalculateHeight(randX, randZ);
Instantiate(tree, new Vector3(randX, terrainHeight + 10, randZ), new Quaternion(0, 0, 0, 0));
}
}
TerrainData GenerateTerrain(TerrainData terrainData)
{
terrainData.heightmapResolution = width + 1;
terrainData.size = new Vector3 (width, depth, height);
terrainData.SetHeights (0, 0, GenerateHeights ());
return terrainData;
}
float[,] GenerateHeights()
{
float[,] heights = new float[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
heights [x, y] = CalculateHeight (x, y);
}
}
return heights;
}
float CalculateHeight (int x, int y)
{
float xCoord = seed + ((float)x / width * scale);
float yCoord = seed + ((float)y / height * scale);
return Mathf.PerlinNoise (xCoord, yCoord);
}
}
I want the height of the trees to follow the height of the Perlin Noise, but they all are at the same height!
Comment
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
How to reset terrain alpha maps in runtime 1 Answer
Paint trees with scripts? 1 Answer
Scaling and rotaion of terrain trees 1 Answer
Multiple Cars not working 1 Answer