Unity学习笔记--制作PerlinNoise(柏林噪声)地形

这里记录一下用柏林噪声制作Unity随机地形的过程:

  1. 柏林噪声原理:

柏林噪声数学原理介绍
2. 在unity中的应用

C# => static float PerlinNoise(float x, float y); 
柏林噪波是在2D平面浮点值生成的伪随机图案(尽管该技术已经普及到三维或者更多维数,但在Unity还未实现)。

此噪波不是由每个点的完全随机值构成,而是由逐渐增加和减少交错波形图案值构成。此噪波可以作为基本纹理效果,但也可用于动画、生成地形高度图以及其他东西。
(在渲染中的应用:
1.在凸凹贴图中它能很好地模拟火焰、云彩、奇形怪状的岩石,以及树木和大理石表面等;
2.做特效地模拟火焰、云彩等。)
unity中首先建立一个平面,新建Script命名为GenerateTerren,将代码组件赋给plane;
在这里插入图片描述
地形代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GenerateTerren : MonoBehaviour {
    int heightScale =2;      
    float detailScale = 2.0f;    //与heightScale一起调整地形高度和细节
	// Use this for initialization
	void Start ()
    {
        Mesh mesh = this.GetComponent<MeshFilter>().mesh;//获取Mesh网格
        Vector3[] vertices = mesh.vertices;

       //将Mesh网格的每一个顶点用柏林噪声函数处理
        for (int v = 0; v < vertices.Length; v++)
        {
            vertices[v].y = Mathf.PerlinNoise((vertices[v].x + this.transform.position.x) / detailScale,
                                                                        (vertices[v].z + this.transform.position.z) / detailScale)*heightScale;    
            //x和z的参数加上自身位置x和z的偏置量可以让结果看起来更自然。
         }
        mesh.vertices = vertices;//重置顶点
        mesh.RecalculateBounds();//重置网格边界
        mesh.RecalculateNormals();//重置网格法线
        this.gameObject.AddComponent<MeshCollider>();//添加Collider可以让player在地面上走动
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

点击运行后记得设置下材质或贴图,让地形看起来更真实。

猜你喜欢

转载自blog.csdn.net/qq_42434073/article/details/107062654