绘制地图可以用很多种方法,实际接触到的地图都是美术制作好的地图,我们需要取灰度图,通过灰度图确认地形起伏,另一种随机生成地图的方法是我们今天主要说的,那就是通过PerlinNoise随机生成地图
1、第一部首先就是通过柏林噪音绘制随机的灰度图
图片最终结果如下:
生成的代码如下:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class CreatTexture : MonoBehaviour
{
//设置图片的大小为128,顶点数不超过65000
int wh = 128;
// Start is called before the first frame update
void Start()
{
Texture2D texture = new Texture2D(wh, wh);
for (int x = 0; x < wh; x++)
{
for (int y = 0; y < wh; y++)
{
//通过perlinNoise生成灰度图
float p = Mathf.PerlinNoise(x * 0.1f, y * 0.1f);
Color color = new Color(p, p, p, 1);
texture.SetPixel(x, y, color);
}
}
texture.Apply();
File.WriteAllBytes(Application.dataPath + "/Demo5/map.png", texture.EncodeToPNG());
}
// Update is called once per frame
void Update()
{
}
}
接下来创建一个空物体和plane,在空物体上写入创建地形的代码,将生成的图片拖到plane上:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class CreatTerrain : MonoBehaviour
{
public int w;
public int h;
void Start()
{
Texture2D texture = GetComponent<Renderer>().material.mainTexture as Texture2D;
VertexHelper vh = new VertexHelper();
w = texture.width;
h = texture.height;
for (int x = 0; x <= w; x++)
{
for (int z = 0; z <= h; z++)
{
float y = texture.GetPixel(x, z).grayscale;
float uvx = (float)x / texture.width;
float uvy = (float)z / texture.height;
vh.AddVert(new Vector3(x-64, y, z-64), Color.white, new Vector3(uvx, uvy));
if (x < w && z < h)
{
vh.AddTriangle(x * (h + 1) + z, x * (h + 1) + z + 1, (x + 1) * (h + 1) + z + 1);
vh.AddTriangle(x * (h + 1) + z, (x + 1) * (h + 1) + z + 1, (x + 1) * (h + 1) + z);
}
}
}
Mesh mesh = new Mesh();
vh.FillMesh(mesh);
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshFilter>().sharedMesh = mesh;
}
}
最终效果图如下:
如果单纯的黑白图不好看的话,我们可以通过Shader修改对应的texture
打开shader代码,调整显示名称:
修改顶点着色器和片元着色器:
最终效果如下: