Using the Unity docs page on Perlin noise, I made this script:
// Width and height of the texture in pixels.
public int pixWidth;
public int pixHeight;
// The origin of the sampled area in the plane.
public float xOrg;
public float yOrg;
// The number of cycles of the basic noise pattern that are repeated
// over the width and height of the texture.
public float scale = 1.0F;
private Texture2D noiseTex;
private Color[] pix;
private Renderer rend;
void Start()
{
rend = GetComponent<Renderer>();
scale = Random.Range(15, 20);
xOrg = Random.Range(0, 20);
yOrg = Random.Range(0, 20);
// Set up the texture and a Color array to hold pixels during processing.
noiseTex = new Texture2D(pixWidth, pixHeight);
pix = new Color[noiseTex.width * noiseTex.height];
rend.material.mainTexture = noiseTex;
}
void CalcNoise()
{
// For each pixel in the texture...
float y = 0.0F;
while (y < noiseTex.height)
{
float x = 0.0F;
while (x < noiseTex.width)
{
float xCoord = xOrg + x / noiseTex.width * scale;
float yCoord = yOrg + y / noiseTex.height * scale;
float sample = Mathf.PerlinNoise(xCoord, yCoord);
pix[(int)y * noiseTex.width + (int)x] = new Color(sample, sample, sample);
x++;
}
y++;
}
// Copy the pixel data to the texture and load it into the GPU.
noiseTex.SetPixels(pix);
noiseTex.Apply();
}
void Update()
{
CalcNoise();
}
The only difference between this code and the Unity docs example is that I added some randomness to the size and origin points of the texture.
I attached the script to a plane, and now when I run the game, the plane has a random noise texture on it.
Now I want the texture to give height to the mesh, so it will look like a terrain. How do I do this?