效果如下:
我们生成的这个地图是一定限制的,不是无限大,可以通过面板去调整凹凸部分的颜色以及大小。
代码如下:
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
public class DItu : MonoBehaviour
{
public Texture2D texture;
public int wh = 128;
public int wid;
public int hig;
public float p = 0.1f;
public Color gao;
public Color di;
// Start is called before the first frame update
void Start()
{
VertexHelper vh=new VertexHelper();
texture = new Texture2D(wh, wh);
for(int x = 0; x < wh; x++)
{
for(int y=0;y < wh; y++) {
float noise = Mathf.PerlinNoise((x + wh * wid) * p,(y+wh*hig)*p);
float z=noise*4;
Color color=Color.Lerp(gao,di,noise);
texture.SetPixel(x,y,color);
float uvx = (float)x /(float) wh;
float uvy = (float)y / (float)wh;
vh.AddVert(new Vector3(x, z, y), color, new Vector2(uvx, uvy));
if(x < wh-1&&y<wh-1) {
vh.AddTriangle(x * wh + y, x * wh + y + 1, (x + 1) * wh + y + 1);
vh.AddTriangle(x * wh + y, (x + 1) * wh + y + 1, (x + 1) * wh + y);
}
}
}
texture.Apply();
Mesh mesh=new Mesh();
vh.FillMesh(mesh);
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshCollider>().sharedMesh = mesh;
GetComponent<MeshRenderer>().material.mainTexture= texture;
}
}