using UnityEngine;
using UnityEngine.UI;
public class CreatTerrain : MonoBehaviour
{
public Texture2D texture;
//使用图片生成地形
void Start()
{
//获取图片像素值
int w = texture.width;
int h = texture.height;
VertexHelper vh = new VertexHelper();
for (int x = 0; x < w; x++)
{
for (int z = 0; z < h; z++)
{
//获取像素颜色
Color color = texture.GetPixel(x, z);
//从颜色中获取灰度值 作为地形高度
float y = color.grayscale;
var uvx = (float) x / (float) w;
var uvy = (float) z / (float) h;
//修改顶点起伏
vh.AddVert(new Vector3(x, y, z), Color.white, new Vector2(uvx, uvy));
if (x != w - 1 && z != h - 1)
{
vh.AddTriangle(x * h + z, x * h + z + 1, (x + 1) * h + z + 1);
vh.AddTriangle(x * h + z, (x + 1) * h + z + 1, (x + 1) * h + z);
}
}
}
//添加到绘制
Mesh mesh = new Mesh();
vh.FillMesh(mesh);
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshCollider>().sharedMesh = mesh;
//修改材质球贴图
Material material = new Material(Shader.Find("Standard"));
material.mainTexture = texture;
GetComponent<MeshRenderer>().material = material;
}
}
使用图片修改Plane地形
最新推荐文章于 2023-02-26 22:40:41 发布