Unity 等比映射小地图

等比映射小地图

其实等比映射小地图非常简单,而且特别节省性能,使用第二摄像机+Rendertexture方式实现小地图,操作起来是简单,但是相对来说它的性能消耗也很大,对于开发人员来说,一定要做到控制性能的优化,才能让自己项目的体验更加流畅,更加吸引人!

闲话少说上代码


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

public class MiniMap : MonoBehaviour {
    /// 
    /// 大地型对象
    /// 
    public GameObject Plane;
    /// 
    /// 玩家对象
    /// 
    public GameObject Player;
    /// 
    /// 小地图贴图
    /// 
    public Texture MapTexture;
    /// 
    /// 小地图玩家贴图
    /// 
    public Texture PlayerTexture;
    /// 
    /// 大地型宽度
    /// 
    private float MaxMapWidth;
    /// 
    /// 大地型高度
    /// 
    private float MaxMapHeight;
    /// 
    /// 玩家在小地图的位置宽度
    /// 
    private float MinMapWidth;
    /// 
    /// 玩家在小地图的位置高度
    /// 
    private float MinMapHeight;
    /// 
    /// 大地图默认宽度
    /// 
    private float MaxMapRealyWidth;
    /// 
    /// 大地图默认高度
    /// 
    private float MaxMapRealyHeight;
    /// 
    /// 玩家当前在地图中的宽度
    /// 
    private float PlayerInMapWidth;
    /// 
    /// 玩家当前在地图中的高度
    /// 
    private float PlayerInMapHeight;

    private void Start()
    {
        MaxMapRealyWidth = Plane.GetComponent().mesh.bounds.size.x;
        MaxMapRealyHeight = Plane.GetComponent().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;

如果还有看不懂的地方,评论留下你的疑惑,定会及时为你解决

你可能感兴趣的:(unity)