根据图片生成地形

 

注意事项: 图片中需要允许设置读写  不打勾会报错

 

效果

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CreatTerrtin : MonoBehaviour
{

public Texture2D texture;//纹理
public int differenceValue;//灰度值倍数
int w = 128;
int h = 128;

public int wnum;
public int hnum;
// Start is called before the first frame update
void Start()
{

//顶点是有个数限制的最多65000个
//纹理尽力取2的次方
wnum = texture.width / w;
hnum = texture.height / h;
//补缝用
int w2 = w + 2;
int h2 = h + 2;

for (int i = 0; i < wnum; i++)
{
for (int j = 0; j < hnum; j++)
{
GameObject terr = new GameObject();
terr.transform.parent = transform;
//顶点助手
VertexHelper vh = new VertexHelper();
for (int x = 0; x < w2; x++)
{
for (int z = 0; z < h2; z++)
{
//获取像素颜色
Color color = texture.GetPixel(w * i + x, h * j + z);//GetPixel 获取像素
//通过灰度图获得高度
float y = color.grayscale* differenceValue;//grayscale灰度值 0-1 differenceValue 数越大 凸起越明显
//计算UV坐标
float uvx = (float)(w * i + x) / (float)(texture.width - 1);
float uvy = (float)(h * j + z) / (float)(texture.height - 1);

vh.AddVert(new Vector3(w * i + x, y, h * j + z), Color.white, new Vector2(uvx, uvy));

if (x < w2-1 && z < h2-1)
{
vh.AddTriangle(x * h2 + z, x * h2 + z + 1, (x + 1) * h2 + z + 1); //0 1 5
vh.AddTriangle(x * h2 + z, (x + 1) * h2 + z + 1, (x + 1) * h2 + z);//0 5 4
}
}

}

Mesh mesh = new Mesh();
vh.FillMesh(mesh);//占满网格


//添加
terr.AddComponent<MeshFilter>().mesh = mesh;
Material material = new Material(Shader.Find("Standard"));//材质球
material.mainTexture = texture;//给材质球纹理
terr.AddComponent<MeshRenderer>().material = material;//赋值材质球
terr.AddComponent<MeshCollider>().sharedMesh = mesh;

}

}

}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值