用Unity绘制地图

绘制地图可以用很多种方法,实际接触到的地图都是美术制作好的地图,我们需要取灰度图,通过灰度图确认地形起伏,另一种随机生成地图的方法是我们今天主要说的,那就是通过PerlinNoise随机生成地图

1、第一部首先就是通过柏林噪音绘制随机的灰度图

图片最终结果如下:

 生成的代码如下:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
 
public class CreatTexture : MonoBehaviour
{
//设置图片的大小为128,顶点数不超过65000
    int wh = 128; 
    // Start is called before the first frame update
    void Start()
    {
        Texture2D texture = new Texture2D(wh, wh);
        for (int x = 0; x < wh; x++)
        {
            for (int y = 0; y < wh; y++)
            {
//通过perlinNoise生成灰度图
                float p = Mathf.PerlinNoise(x * 0.1f, y * 0.1f);
                Color color = new Color(p, p, p, 1);
                texture.SetPixel(x, y, color);
            }
        }
        texture.Apply();
        File.WriteAllBytes(Application.dataPath + "/Demo5/map.png", texture.EncodeToPNG());
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
}

接下来创建一个空物体和plane,在空物体上写入创建地形的代码,将生成的图片拖到plane上:


using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
 
public class CreatTerrain : MonoBehaviour
{
    public int w;
    public int h;
    void Start()
    {
        Texture2D texture = GetComponent<Renderer>().material.mainTexture as Texture2D;
        VertexHelper vh = new VertexHelper();
        w = texture.width;
        h = texture.height;
        for (int x = 0; x <= w; x++)
        {
            for (int z = 0; z <= h; z++)
            {
                float y = texture.GetPixel(x, z).grayscale;
                float uvx = (float)x / texture.width;
                float uvy = (float)z / texture.height;
                vh.AddVert(new Vector3(x-64, y, z-64), Color.white, new Vector3(uvx, uvy));
                if (x < w && z < h)
                {
                    vh.AddTriangle(x * (h + 1) + z, x * (h + 1) + z + 1, (x + 1) * (h + 1) + z + 1);
                    vh.AddTriangle(x * (h + 1) + z, (x + 1) * (h + 1) + z + 1, (x + 1) * (h + 1) + z);
                }
            }
        }
 
        Mesh mesh = new Mesh();
        vh.FillMesh(mesh);
        GetComponent<MeshFilter>().mesh = mesh;
        GetComponent<MeshFilter>().sharedMesh = mesh;
    }
}

最终效果图如下:

 如果单纯的黑白图不好看的话,我们可以通过Shader修改对应的texture

 打开shader代码,调整显示名称:

修改顶点着色器和片元着色器:

 最终效果如下:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值