UnityMesh绘制地形

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()
    {
        
    }
}

生成的地形如下:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值