Skip to content
Snippets Groups Projects
TerrainGenerator.cs 1.44 KiB
Newer Older
Chang, Ryan's avatar
Chang, Ryan committed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public struct Octave
{
    public float amplitude;
    public float frequency;
}

[System.Serializable]
public enum NoiseType
{
    Perlin,
    Simplex,
    Celluar
Chang, Ryan's avatar
Chang, Ryan committed
}

public class TerrainGenerator : MonoBehaviour
{
    public Terrain terrain;

    public NoiseType type;

    public List<Octave> octaves;

    public bool refresh;
Chang, Ryan's avatar
Chang, Ryan committed

    [Tooltip("How fine grain the generated terrain will be. Larger values = more precise.")]
    public int xSamples = 1000, ySamples = 1000;
Chang, Ryan's avatar
Chang, Ryan committed

    private void Start()
    {
        float[,] heights = new float[xSamples, ySamples];

        //float xRes = (terrain.terrainData.size.x / xSamples);
        //float yRes = (terrain.terrainData.size.y / ySamples);

        Vector2 startPerlinPos = RNG.GetRandomVector2(-xSamples, -ySamples, xSamples, ySamples);
Chang, Ryan's avatar
Chang, Ryan committed
        
        foreach (var octave in octaves)
        {
            for (int x = 0; x < xSamples; x++)
            {
                for (int y = 0; y < ySamples; y++)
                {
                    heights[x, y] += Mathf.PerlinNoise(x * octave.frequency + startPerlinPos.x, y * octave.frequency + startPerlinPos.y) * octave.amplitude;
                }
            }
        }

        terrain.terrainData.SetHeights(0, 0, heights);
    }

    private void Update()
    {
        if (refresh)
        {
            refresh = false;
            Start();
        }
Chang, Ryan's avatar
Chang, Ryan committed
    }
}