본문 바로가기
개발/C#

유니티 C# 랜덤 지형 생성하기 간단 구현 Perlin noise

by SPNK 2023. 4. 23.
반응형
  • 코드 작성
using UnityEngine;

public class TerrainGenerator : MonoBehaviour
{
    public int width = 256;
    public int height = 256;
    public float scale = 20.0f;

    public int octaves = 3;
    public float persistence = 0.5f;
    public float lacunarity = 2.0f;

    public int seed = 0;

    private void Start()
    {
        Terrain terrain = GetComponent<Terrain>();
        terrain.terrainData = GenerateTerrain(terrain.terrainData);
    }

    private TerrainData GenerateTerrain(TerrainData terrainData)
    {
        terrainData.heightmapResolution = width + 1;
        terrainData.size = new Vector3(width, 600, height);

        terrainData.SetHeights(0, 0, GenerateHeights());

        return terrainData;
    }

    private 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;
    }

    private float CalculateHeight(int x, int y)
    {
        float amplitude = 1;
        float frequency = 1;
        float height = 0;

        for (int i = 0; i < octaves; i++)
        {
            float xCoord = (float)x / width * scale * frequency + seed;
            float yCoord = (float)y / height * scale * frequency + seed;

            float noise = Mathf.PerlinNoise(xCoord, yCoord);
            height += noise * amplitude;

            amplitude *= persistence;
            frequency *= lacunarity;
        }

        return height;
    }
}

 

  • width: 지형의 너비
  • height: 지형의 높이
  • scale: Perlin noise의 크기
  • octaves: Perlin noise의 옥타브 수
  • persistence: 옥타브별 진폭 감소율
  • lacunarity: 옥타브별 주파수 증가율
  • seed: Perlin noise의 시드값
반응형

댓글