除了使用自带的Terrain(地形)生成地图之外还可以使用Mesh网格生成地图,地图的高低起伏以及随机可以使用柏林噪声实现:
public class CreateMap : MonoBehaviour
{
[SerializeField]
[Range(2, 250)]
int x, y;
private void Start()
{
DrawMap();
}
private void DrawMap()
{
VertexHelper vh = new VertexHelper();
Texture2D t2d = new Texture2D(x, y);
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
float rx = Random.Range(0.02f, 0.02f);
float ry = Random.Range(0.02f, 0.02f);
float h = Mathf.PerlinNoise(i * 0.02f + rx, j * 0.02f + ry);
float uvx = (float)i / (x - 1);
float uvy = (float)j / (y - 1);
t2d.SetPixel(i, j, Color.white);
vh.AddVert(new Vector3(i, h * 20, j), Color.white, new Vector2(uvx, uvy));
if (i != x - 1 && j != y - 1)
{
vh.AddTriangle(i * y + j, i * y + j + 1, (i + 1) * y + j + 1);
vh.AddTriangle(i * y + j, (i + 1) * y + j + 1, (i + 1) * y + j);
}
}
}
t2d.Apply();
Mesh mesh = new Mesh();
vh.FillMesh(mesh);
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshCollider>().sharedMesh= mesh;
GetComponent<MeshRenderer>().material.mainTexture = t2d;
}
}
效果如下:
这样我们就有了简单的地图,接下来给地图添加颜色作为高低的区分:
Color color = Color.Lerp(color1, color2, h);
t2d.SetPixel(i, j, color);
vh.AddVert(new Vector3(i, h * 20, j), color, new Vector2(uvx, uvy));
根据高度的不同给与每个顶点不同的颜色:
然后利用生成的柏林噪声图制作一个简单的小地图:
在给角色加上简单的移动脚本以及相机跟随脚本:
public class CameraFollow : MonoBehaviour
{
public Transform player;
private void LateUpdate()
{
if (player != null)
{
transform.position = Vector3.Lerp(transform.position, player.position, Time.deltaTime * 8);
}
}
}
public class Player : MonoBehaviour
{
private void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 dir = new Vector3(h, 0, v);
if (dir != Vector3.zero)
{
transform.LookAt(dir + transform.position);
transform.Translate(Vector3.forward * Time.deltaTime);
}
}
}
然后通过计算角色在地图上的位置比值调整小地图图片的位置,就可以实现小地图同步跟随角色一起移动