两种绘制地图的方法
每个游戏都有自己的地图,今天我们就绘制一些简单的地图,而不是一直用3D Object里面的Plane 平面的当做地图。
首先我们需要在场景中先创建一个Plane和一个空对象。 (Plane是用来看效果的)
创建两个脚本CreatTexture和CreatTerrain
把CreatTerrain脚本挂在Plane上,在Plane上先拖一个图片
我的图片本来是一个大乔的头像,之所以变成这样是因为我已经提前写过一遍,重新生成出来的png图片。
空对象上挂 CreatTexture
记得将自己的图片的宽高打开 不然执行代码的时候会报错
先写CreatTerrain脚本
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class CreatTerrain : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Texture2D texture = GetComponent<Renderer>().material.mainTexture as Texture2D; //先获取图片
VertexHelper vh = new VertexHelper(); //顶点助手
int w = texture.width;
int h = texture.height; //这里的宽高要/10 如果不/10会因为太大,Unity只能绘制36000的图片,所以宽高要/10
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.width;
vh.AddVert(new Vector3(x, y, z), Color.white, new Vector2(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<MeshCollider>().sharedMesh = mesh;
AssetDatabase.CreateAsset(mesh, "Assets/mymesh.asset"); //生成我们需要的地图图片
}
// Update is called once per frame
void Update()
{
}
}
宽高在生成完图片以后就可以把/10给去掉
然后我们需要打包Mesh
在CreatTexture脚本里面写
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class CreatTexture : MonoBehaviour
{
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++)
{
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 + "/Demo1/map.png", texture.EncodeToPNG());
}
// Update is called once per frame
void Update()
{
}
}
将这些做完以后直接把打包出来的Mesh直接拖到Plane上
这样一个简单的地图就绘制完成了;
如果感觉这种地图不好看的话,就需要我们自己去官方下载一些资源。
我提前下载好了一个绿地的资源包
这里就直接用了。
用资源绘制地图的话跟之前不太一样。
首先我们要右键在Creat里面找到Shader里面的第二个Shader
创建出来之后我们还要创建一个材质球
这样调好之后打开我们创建的Shader之后
将这两个改成这样,在高级保存现象中把编码调成UTF-8
这是我们需要改动的地方
改完之后在材质球中就能将我们下载好的资源图片拖到里面去
这个就是我利用资源绘制好的地图。