unity 简易的小地图导航

先上效果图↓↓↓

unity 简易的小地图导航

1. 先是制作小地图

  • 在Project面板中创建一个RenderTexture,将这个RenderTexture放在Camera中的TargetTexture中
  • 新建一个RawImage对象,将RenderTexture赋值给它

2. 实现点击小地图位置,真实位置也随之改变

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.AI;

/// <summary>
/// 该脚本挂在小地图上
/// </summary>
public class Move : MonoBehaviour,IPointerClickHandler
{
    public GameObject player;//需要移动的对象
    public GameObject plane; //移动的实际平台(该平台初始坐标是(0,0,0))
    private float mapWidth;
    private float mapHeight;
    private float planeWidth;
    private float planeHeight;
    private Vector2 tempVector;//移动的目标

    // Use this for initialization
    void Start ()
    {
        mapWidth = this.GetComponent<RectTransform>().rect.width;
        mapHeight = this.GetComponent<RectTransform>().rect.height;
        planeWidth = plane.GetComponent<MeshRenderer>().bounds.size.x;
        planeHeight = plane.GetComponent<MeshRenderer>().bounds.size.z;
    }
	
	// Update is called once per frame
	void Update ()
	{
	    player.transform.position = Vector3.Lerp(player.transform.position,new Vector3(tempVector.x,0,tempVector.y), Time.deltaTime*0.5f);
	}

    //点击事件
    public void OnPointerClick(PointerEventData eventData)
    {
        //鼠标点击在小地图的位置
        tempVector = new Vector2(eventData.position.x - Screen.width + mapWidth, eventData.position.y - Screen.height + mapHeight);
        Debug.Log(tempVector);

        //小地图位置映射到具体的位置
        tempVector = new Vector2((tempVector.x/mapWidth)*planeWidth - planeWidth/2,(tempVector.y/mapHeight)*planeHeight-planeHeight/2);
        Debug.Log(tempVector);


    }

}