Unity 等比映射小地圖

等比映射小地圖

其實等比映射小地圖非常簡單,而且特別節省性能,使用第二攝像機+Rendertexture方式實現小地圖,操作起來是簡單,但是相對來說它的性能消耗也很大,對於開發人員來說,一定要做到控制性能的優化,才能讓自己項目的體驗更加流暢,更加吸引人!

閒話少說上代碼


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MiniMap : MonoBehaviour {
    /// <summary>
    /// 大地型對象
    /// </summary>
    public GameObject Plane;
    /// <summary>
    /// 玩家對象
    /// </summary>
    public GameObject Player;
    /// <summary>
    /// 小地圖貼圖
    /// </summary>
    public Texture MapTexture;
    /// <summary>
    /// 小地圖玩家貼圖
    /// </summary>
    public Texture PlayerTexture;
    /// <summary>
    /// 大地型寬度
    /// </summary>
    private float MaxMapWidth;
    /// <summary>
    /// 大地型高度
    /// </summary>
    private float MaxMapHeight;
    /// <summary>
    /// 玩家在小地圖的位置寬度
    /// </summary>
    private float MinMapWidth;
    /// <summary>
    /// 玩家在小地圖的位置高度
    /// </summary>
    private float MinMapHeight;
    /// <summary>
    /// 大地圖默認寬度
    /// </summary>
    private float MaxMapRealyWidth;
    /// <summary>
    /// 大地圖默認高度
    /// </summary>
    private float MaxMapRealyHeight;
    /// <summary>
    /// 玩家當前在地圖中的寬度
    /// </summary>
    private float PlayerInMapWidth;
    /// <summary>
    /// 玩家當前在地圖中的高度
    /// </summary>
    private float PlayerInMapHeight;

    private void Start()
    {
        MaxMapRealyWidth = Plane.GetComponent<MeshFilter>().mesh.bounds.size.x;
        MaxMapRealyHeight = Plane.GetComponent<MeshFilter>().mesh.bounds.size.z;
        //得到大地圖高度縮放地理
        float scal_z = Plane.transform.localScale.z;
        MaxMapRealyHeight = MaxMapRealyHeight * scal_z;
        //得到大地圖高度縮放地理
        float scal_x = Plane.transform.localScale.x;
        MaxMapRealyWidth = MaxMapRealyWidth * scal_x;
        Check();
    }

    private void FixedUpdate()
    {
        Check();
    }

    private void OnGUI()
    {
        GUI.DrawTexture(new Rect(Screen.width - MapTexture.width/4, 0, MapTexture.width/4, MapTexture.height/4), MapTexture);
        GUI.DrawTexture(new Rect(MinMapWidth, MinMapHeight, 20, 20), PlayerTexture);
    }

    void Check()
    {
        //根據比例計算小地圖“主角”的座標
        MinMapWidth = (MapTexture.width * Player.transform.position.x/ MaxMapRealyWidth) + ((MapTexture.width /4 / 2) - (20 / 2)) + (Screen.width - MapTexture.width/4);
        MinMapHeight = MapTexture.height/4 - ((MapTexture.height/4 * Player.transform.position.z / MaxMapRealyHeight) + (MapTexture.height / 4/ 2 + 30));
    }

}

其中有四個需要拖拽的Public的遊戲對象
plane —-> 就是你的地形
player —-> 就是你的主角
MapTexture —-> 就是小地圖紋理
playerTexture —-> 就是代表主角的紋理
計算原理
1.首先計算小地圖的位置
小地圖假設放到右上角,那麼小地圖的位置起點就應該是屏幕寬度減去小地圖本身的寬度,高就是0
2.其次計算玩家紋理在小地圖上的位置
我們就拿玩家在場景的左下角出生爲例,那麼玩家在小地圖上也應該是在小地圖的左下角纔是正確的,首先先把玩家放到小地圖的左下角,那麼玩家在小地圖的x應該是屏幕寬度減去小地圖寬度,y應該是小地圖的高度,第一步完成,第二步如果玩家移動,那麼小地圖上玩家也要動,怎麼動是需要計算的,首先求出小地圖和大地圖的比例,然後乘上玩家的x,z就的到了玩家應該在小地圖上移動的x,y;

如果還有看不懂的地方,評論留下你的疑惑,定會及時爲你解決

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章