在数学类中我们经常看到下面的代码
Mathf.PerlinNoise
这个究竟是什么意思呢?
我们来看看起源
在上世纪80年代,柏林噪声的发明者Ken Perlin尝试用普通噪声模拟随机效果,用于正在制作的经典迪士尼电影电子世界争霸战(TRON),但一直无法得到满意的效果,柏林噪声算法就这样应运而生。
应用篇
柏林噪声
自然界中层叠的山峦,大理石的纹理,海面高低起伏的波浪,这些现象看似杂乱无章,却都有内在规律可循,普通的噪声无法模拟出这些自然效果,柏林噪声算法使这些成为可能。
我们来看看代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class 柏林噪声 : MonoBehaviour
{
public MeshFilter filter;
public MeshRenderer renderer;
public MeshCollider collider;
public Texture2D gao;
public Texture2D di;
public int w;
public int h;
public Texture2D texture;
void Start()
{
Mesh mesh = new Mesh();
VertexHelper vh = new VertexHelper();
//texture = new Texture2D(w*gao.width,h*gao.height); 材质小的情况
texture = new Texture2D(w,h); //材质和生成地图差不多的情况
for (int i = 0; i <= w; i++)
{
for (int j = 0; j <= h; j++)
{
// 计算Perlin噪声值
float perlinValue = Mathf.PerlinNoise(i * 0.1f, j * 0.1f);
float uvx = i / (float)w; //正方形 哔哩
float uvy = j / (float)h;
//如果图比较小 我们就要计算插值
//for (int x = 0; x < gao.width; x++)
//{
// for (int y = 0; y < gao.height; y++)
// {
// Color gaocolor = gao.GetPixel(x,y);
// Color dicolor = di.GetPixel(x, y);
// texture.SetPixel(i * gao.width + x, j * gao.height + y,Color.Lerp(dicolor,gaocolor,perlinValue));
// }
//}
Color gaocolor = gao.GetPixel(i, j); //获取颜色
Color dicolor = di.GetPixel(i, j); //获取颜色
texture.SetPixel(i, j , Color.Lerp(dicolor, gaocolor, perlinValue));
// 根据Perlin噪声值设置高度
// float height = perlinValue * 2f; // 将Perlin噪声值映射到0到2的范围内
// 添加顶点并根据高度选择材质
//if (height > 1f)
//{
// vh.AddVert(new Vector3(i, height, j), Color.red, new Vector2(uvx, uvy));
//}
//else
//{
vh.AddVert(new Vector3(i, perlinValue * 10, j), Color.white, new Vector2(uvx, uvy));
//}
if (i != w && j != h)
{
vh.AddTriangle(i * (h + 1) + j, i * (h + 1) + j + 1, (i + 1) * (h + 1) + j);
vh.AddTriangle(i * (h + 1) + j + 1, (i + 1) * (h + 1) + j + 1, (i + 1) * (h + 1) + j);
}
}
}
texture.Apply();//保存信息
vh.FillMesh(mesh);
filter.mesh = mesh;
renderer.material.mainTexture = texture;
collider.sharedMesh = mesh;
}
}
初始化
第一个是网格过滤器
第二个是网格渲染器
第三个就是网格碰撞器
gao 材质
DI 材质
w 宽度
h数量
teture //默认材质
扩展
sharedMateial 只会变自己
Mateial 会变所有
打开read