先定义地图长和宽(x,y)使用柏林噪音算法生成随机点位,绘制出灰度图
根据图片的灰度值获取绘制点位信息,再添加绘制顺序,最后给MeshFilter赋值mesh网格信息
最后生成随机地形如图
代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Drawmap : MonoBehaviour
{
int x = 50,y=50;
// Start is called before the first frame update
void Start()
{
VertexHelper vh = new VertexHelper();
Texture2D used = new Texture2D(x, x);
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
//float rx = Random.Range(-0.02f, 0.02f);
//float ry = Random.Range(-0.02f, 0.02f);
float height = Mathf.PerlinNoise(i * 0.05f , j * 0.05f );
float uvx = (float)i / (x - 1);
float uvy = (float)j / (y - 1);
Color color = GetColor(height);
used.SetPixel(i, j, color);
vh.AddVert(new Vector3(i, height * 5, j), color, new Vector2(uvx, uvy));
if (i!=x-1&&j!=y-1)
{
vh.AddTriangle(i * y + j, i * y + j + 1, (i + 1) * y + j + 1);
vh.AddTriangle(i * y + j, (i + 1) * y + j + 1, (i + 1) * y + j);
}
}
}
used.Apply();
Mesh mesh = new Mesh();
vh.FillMesh(mesh);
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshCollider>().sharedMesh = mesh;
GetComponent<MeshRenderer>().material.mainTexture = used;
}
private Color GetColor(float height)
{
return Color.Lerp(Color.blue, Color.green, height);
}
}