Unity程序化地形教程 第二期 噪声图的完善和更多细节添加
前言:完整的程序化地形教程在我的主页相关专栏中,目前正在持续更新,可以添加收藏,方便日后查找
零、学完本期能够实现的效果
书接上期,学完之后相比上期能够有更多的细节和优化,话不多说,赶快开始吧!
一、noise脚本的属性值添加
相比上一期noise的属性值,这一期里面新添加了五个属性值,我们在上图中也能看到相关的效果,这五个值分别是
public int octaves;
public float persistance;
public float lacunarity;
public int seed;
public Vector2 offset;
在这里我们添加上相关属性后的代码,各个函数都有相关的注释
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Noise
{
public static float[,] GenerateNoiseMap(int mapWidth,int mapHeight,int seed, float scale,int octaves,float persistance,float lacunarity,Vector2 offset)
{
float[,] noiseMap = new float[mapWidth, mapHeight];
System.Random prng = new System.Random(seed);
Vector2[] octaveOffsets = new Vector2[octaves];
for(int i=0;i<octaves;i++)
{
float offsetX = prng.Next(-100000, 100000) + offset.x;
float offsetY = prng.Next(-100000, 100000) + offset.y;
octaveOffsets[i] = new Vector2(offsetX, offsetY);
}
if(scale<=0)
{
scale = 0.0001f;
}
float maxNoiseHeight = float.MinValue;
float minNoiseHeight = float.MaxValue;
float halfwidth = mapWidth / 2f;
float halfHeight = mapHeight / 2f;
for (int y =0;y<mapHeight;y++)
{
for(int x=0;x<mapWidth;x++)
{
float amplitude = 1;
float frequency = 1;
float noiseHeight = 0;
for(int i =0;i<octaves;i++)
{
float sampleX = (x-halfwidth) / scale *frequency +octaveOffsets[i].x;
float sampleY = (y-halfHeight)/ scale*frequency+octaveOffsets[i].y;
float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
noiseMap[x, y] = perlinValue;
noiseHeight += perlinValue * amplitude;
amplitude *= persistance;
frequency *= lacunarity;
}
if(noiseHeight>maxNoiseHeight)
{
maxNoiseHeight = noiseHeight;
}
else if(noiseHeight<minNoiseHeight)
{
minNoiseHeight = noiseHeight;
}
noiseMap[x, y] = noiseHeight;
}
}
for (int y = 0; y < mapHeight; y++)
{
for (int x = 0; x < mapWidth; x++)
{
noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
}
}
return noiseMap;
}
}
二、地图生成器MapGenerator脚本的属性添加
很好理解,地图生成器是根据noise脚本为基础来创造噪声图的,noise脚本中修改的属性也要在这个脚本中进行更改
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapGenerator : MonoBehaviour
{
public int mapWidth;
public int mapHeight;
public float noiseScale;
public int octaves;
[Range(0,1)]
public float persistance;
public float lacunarity;
public int seed;
public Vector2 offset;
public bool autoUpdate;
public void GenerateMap()
{
float[,] noiseMap = Noise.GenerateNoiseMap(mapWidth, mapHeight, seed,noiseScale,octaves,persistance,lacunarity,offset);
MapDisplay display = FindObjectOfType<MapDisplay>();
display.DrawNoiseMap(noiseMap);
}
private void OnValidate()
{
if(mapWidth<1)
{
mapWidth = 1;
}
if(mapHeight<1)
{
mapHeight = 1;
}
if(lacunarity<1)
{
lacunarity = 1;
}
if(octaves<0)
{
octaves = 0;
}
}
}
三、最终的效果展示
保存脚本、之后我们就可以在Unity中运行查看效果了,对于不理解的新添属性值,我们可以在Unity的调试界面对这些属性值进行更改,看对于噪声图会发生怎样的变化 这样一个基本的用于控制地形生成的噪波图就制作好了,是不是很有趣呢?感兴趣的话点个关注,后面持续更新!
上期教程连接:Unity程序化地形教程 第一期 噪波图的制作
|