1.首先创建一个地板plane
2.为地板创建一个脚本
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Map : MonoBehaviour
{
public int w=100,h=100;//宽高
Texture2D texture;//2d纹理
public Color color1=Color.cyan,color2=Color.magenta;//颜色
// Start is called before the first frame update
void Start()
{
texture=new Texture2D(w,h);//2d纹理大小
VertexHelper vh=new VertexHelper();//顶点助手
for(int i=0;i<w;i++)//宽
{
for(int j=0;j<h;j++)//高
{
float p=Mathf.PerlinNoise(i*0.3f,j*0.3f);//柏林降噪 地形y高度
texture.SetPixel(i,j,Color.Lerp(color1,color2,p));//渐变颜色
float uvx = (float)i/(float)w;//地图比例宽
float uvy = (float)j/(float)h;//地图比例高
vh.AddVert(new Vector3(i,p,j),Color.white,new Vector2(uvx,uvy));//添加顶点
if(i!=w-1&&j!=h-1)//如果不是最后的值
{
vh.AddTriangle(i * h + j, i * h + j + 1, (i + 1) * h + j + 1);//0,1,101
vh.AddTriangle(i * h + j, (i + 1) * h + j + 1, (i + 1) * h + j);//0,101,100
}
}
}
texture.Apply();//2d纹理赋色
Mesh mesh = new Mesh();//创建mesh网格
vh.FillMesh(mesh);//顶点 填充网格
GetComponent<MeshFilter>().mesh = mesh;//mesh赋值
GetComponent<MeshCollider>().sharedMesh = mesh;//共享网格赋值
GetComponent<MeshRenderer>().material.mainTexture = texture;//主纹理赋值
}
// Update is called once per frame
void Update()
{
}
}
生成的地形如下: