LoginSignup
6
2

More than 3 years have passed since last update.

[Unity] お手軽!Mathf.PerlinNoise で地形を作る

Last updated at Posted at 2020-12-01

こちらは Unity #2 Advent Calendar 2020 の 2日目の記事です

Unityには、(x,y)の値に依存した[0,1]の連続したノイズ値を返すMathf.PerlinNoise(x,y)という数学関数が用意されており、これを使うと地形ステージが簡単に作れます。
例えば、空のオブジェクトに以下のスクリプトをアタッチして実行するとこうなります。

2020-11-05_203911.png

海の領域を減らしたければこう
2020-11-05_204538.png
2020-11-05_204343.png

迷路っぽくしたければこう
2020-11-05_204819.png
2020-11-05_204851.png

ね?簡単でしょ?

PerlinNoiseSample.cs
using UnityEngine;
public class PerlinNoiseSample : MonoBehaviour {
    [SerializeField, Range(0f, 1f)] float m_threshold = 0.5f;
    [SerializeField, Range(0.05f, 0.3f)] float m_scale = 0.1f;
    int sz = 50;

    void Start() {
        createCustomCube(Vector3.zero, new Vector3(sz, 0.1f, sz), new Color(0.4f, 0.3f, 0.9f));
        for (int x = 0; x < sz; ++x) {
            for (int z = 0; z < sz; ++z) {
                float noise = Mathf.PerlinNoise((float)x * m_scale, (float)z * m_scale);
                if (noise < m_threshold) {
                    float thRate = (m_threshold - noise) / (m_threshold);
                    createCustomCube(new Vector3(-sz*0.5f+x, 0f, -sz*0.5f+z), new Vector3(1f,thRate*10f, 1f), new Color(1f-thRate*1.1f, 0.8f+thRate*0.3f, 0.9f-thRate*1.2f));
                }
            }
        }
    }

    void Update(){}

    GameObject createCustomCube(Vector3 _position, Vector3 _scale, Color _color) {
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
        go.transform.SetParent(transform);
        go.transform.localPosition = transform.position + _position;
        go.transform.localScale = _scale;
        go.GetComponent<MeshRenderer>().material.color = _color;
        return go;
    }
}
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2