小地图对于现在的游戏来讲可以说非常普遍,玩家可以通过小地图来了解人物现在的位置以及地形信息,下面我们先看一个简易的效果图:
制作小地图有一个要注意的点,GUI屏幕坐标和世界坐标的转化:
上面我画了两张图,比较难看,但是还是解释了转化的原理,世界坐标和屏幕坐标的x和z均相差了一半地图长度,说直白点,把世界坐标向左和向下移一半就是屏幕坐标。但得到的坐标如果直接赋给小地图上的任务对象那么是该图片的左下角到达该点,所以还需要将人物图片进行坐标的转换也就是将该任务对象的图片向左和向下移一半即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SmallMap : MonoBehaviour {
//游戏对象
GameObject Cube;
//大地图
GameObject Plane;
//小地图
public Texture map;
//小地图上的主角
public Texture Smallcube;
//大地图的尺寸
private float PlaneWidth;
private float PlaneHeight;
//大立方体的位置
private float Cube_X;
private float Cube_Z;
//小立方体的位置
private float smallCube_X=0;
private float smallCube_Z=0;
// Use this for initialization
void Start () {
Cube = GameObject.Find("Cube");
Plane = GameObject.Find("Plane");
//原始mesh的尺寸*localScale.x获得物体Size
PlaneWidth = (Plane.GetComponent<MeshFilter>().mesh.bounds.size.x)*(Plane.transform.localScale.x);
PlaneHeight = (Plane.GetComponent<MeshFilter>().mesh.bounds.size.z)*(Plane.transform.localScale.z);
FindPosition();
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.W))
{
Cube.transform.Translate(Vector3.forward * Time.deltaTime * 5);
FindPosition();
}
if(Input.GetKey(KeyCode.A))
{
Cube.transform.Translate(-Vector3.right * Time.deltaTime * 5);
FindPosition();
}
if(Input.GetKey(KeyCode.S))
{
Cube.transform.Translate(-Vector3.forward * Time.deltaTime * 5);
FindPosition();
}
if(Input.GetKey(KeyCode.D))
{
Cube.transform.Translate(Vector3.right * Time.deltaTime * 5);
FindPosition();
}
}
void OnGUI(){
//绘制小地图背景
GUI.DrawTexture(new Rect(Screen.width - map.width,0, map.width, map.height), map);
//绘制小立方体
GUI.DrawTexture(new Rect(smallCube_X,smallCube_Z, Smallcube.width, Smallcube.height), Smallcube);
}
void FindPosition()
{
Cube_X = Cube.transform.position.x;
Cube_Z = Cube.transform.position.z;
if(Cube_X>=PlaneWidth/2)
Cube_X = PlaneWidth/2;
if(Cube_X<=-PlaneWidth/2)
Cube_X = -PlaneWidth/2;
if(Cube_Z>=PlaneHeight/2)
Cube_Z = PlaneHeight/2;
if(Cube_Z<=-PlaneHeight/2)
Cube_Z = -PlaneHeight/2;
Cube.transform.position = new Vector3(Cube_X,Cube.transform.position.y,Cube_Z);
//根据比例计算小地图“主角”的坐标
//GUI 坐标是左上角为起点和屏幕坐标以左下角为起点
smallCube_X = Cube_X*(map.width/PlaneWidth)+map.width/2+(Screen.width-map.width)-Smallcube.width/2;
smallCube_Z = map.height-(Cube_Z*(map.height/PlaneHeight)+map.height/2)-Smallcube.height/2;
}
}
PS:这个的Plane一定要放到(0,0,0)点,因为所有的计算都基于世界坐标。