首页 > 其他分享 >地形制作

地形制作

时间:2023-02-07 11:56:18浏览次数:30  
标签:int float texture 地形 h2 new 制作 terr

 

 

 

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

 

效果

 

 

 

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;

}

}

}


}

标签:int,float,texture,地形,h2,new,制作,terr
From: https://www.cnblogs.com/qinhuanghan5/p/17097885.html

相关文章