I'm starting now with Perlin Noise, and I have made the following code with that [tutorial][1].
using UnityEngine;
using System.Collections;
public class WorldGen : MonoBehaviour {
public Terrain myterrain;
// The origin of the sampled area in the plane.
float xOrg;
float yOrg;
// The number of cycles of the basic noise pattern that are repeated
// over the width and height of the texture.
float scale = 1.0f;
float[][] sample;
float[][] result;
void Start() {
editTerrain();
}
void Update()
{
}
void editTerrain() {
int pixWidth = myterrain.terrainData.heightmapWidth;
int pixHeight = myterrain.terrainData.heightmapHeight;
float[,] heights = myterrain.terrainData.GetHeights(0, 0, pixWidth, pixHeight);
result = CalcNoise(pixWidth, pixHeight);
for(int z = 0; z < pixHeight; z++) {
for(int x = 0; x < pixWidth; x++) {
float xCos = Mathf.Cos(result[x][z]);
float zSin = -Mathf.Sin(result[x][z]);
heights[x, z] = (xCos - zSin) / Random.Range(100, 1000);
}
}
myterrain.terrainData.SetHeights(0, 0, heights);
}
float[][] CalcNoise(int width, int height)
{
// For each pixel in the texture...
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// Get a sample from the corresponding position in the noise plane
// and create a greyscale pixel from it.
float xCoord = xOrg + x / width * scale;
float yCoord = yOrg + y / height * scale;
sample[x][y] = Mathf.PerlinNoise(xCoord, yCoord);
}
}
return sample;
}
}
[1]: http://docs.unity3d.com/Documentation/ScriptReference/Mathf.PerlinNoise.html
And for some reason, the debug console throw me that error:
NullReferenceException: Object reference not set to an instance of an object
WorldGen.CalcNoise (Int32 width, Int32 height) (at Assets/WorldGen.cs:68)
WorldGen.editTerrain () (at Assets/WorldGen.cs:39)
WorldGen.Start () (at Assets/WorldGen.cs:21)
What can I do?
I think that I made all correct... Or not?
Thanks in advance.
----------
**PD:** I don't know if it's obligatory to use a texture, but I was trying to add directly the floated number to the terrain...
↧