这里对上次的代码做优化,当进入或者地图时,小地图UI也应该进行变化。
调用次序:MapController—>MiniMapManager -->UIminiMap
首先是每个场景都需要有个MapRoot,MapRoot绑定MapController脚本,且该节点需要有该地图的一个MiniMapBoundingBox(见上一篇文章) 在进入地图时调用单例的MiniMapManager
public class MapController : MonoBehaviour
{
public Collider minimapBoundingBox;
// Start is called before the first frame update
void Start()
{
MiniMapManager.Instance.UpdateMinimap(minimapBoundingBox);
}
// Update is called once per frame
void Update()
{
}
}
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Managers
{
class MiniMapManager : Singleton<MiniMapManager>
{
private Collider minimapBoundingBox;
public UIMiniMap miniMap;
public Collider MinimapBoundingBox
{
get { return minimapBoundingBox; }
}
public Transform PlayerTransform
{
get
{
if (User.Instance.CurrentCharacterObj == null) return null;
return User.Instance.CurrentCharacterObj.transform;
}
}
public Sprite LoadCurrentMiniMap()
{
return Resources.Load<Sprite>("UI/MiniMap/" + User.Instance.CurrentMapData.MiniMap);
}
public void UpdateMinimap(Collider minimapBoundingBox)
{
this.minimapBoundingBox = minimapBoundingBox;
if (this.miniMap != null)
{
this.miniMap.UpdateMap();
}
}
}
}
using Models;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Managers;
public class UIMiniMap : MonoBehaviour
{
public Image minimap;
public Image arrow;//角色箭头
public Text MapName;
private Transform playerTransform;
public Collider MinimapBoundingBox;
void Start()
{
MiniMapManager.Instance.miniMap = this;
this.UpdateMap();
}
public void UpdateMap()
{
this.MapName.text = User.Instance.CurrentMapData.Name;
this.minimap.overrideSprite = MiniMapManager.Instance.LoadCurrentMiniMap();
this.minimap.SetNativeSize();
this.minimap.transform.localPosition = Vector3.zero;
this.MinimapBoundingBox = MiniMapManager.Instance.MinimapBoundingBox;
this.playerTransform = null;//进入新地图玩家的实例不是上个图的,因此需要清理掉 在update重新获取
}
// Update is called once per frame
void Update()//坐标转换:世界坐标->小地图坐标
{
this.UpdateMap();
if (playerTransform == null)
{
this.playerTransform = MiniMapManager.Instance.PlayerTransform;//获取角色对象实例
}
if (MinimapBoundingBox == null || playerTransform == null) return;
float realWidth = this.MinimapBoundingBox.bounds.size.x;
float realHeight = this.MinimapBoundingBox.bounds.size.z;
float relaX = playerTransform.position.x - MinimapBoundingBox.bounds.min.x;//MinimapBoundingBox.bounds.min.x->碰撞体左下角的X坐标
float relaY = playerTransform.position.z - MinimapBoundingBox.bounds.min.z;
float pivotX = relaX / realWidth;
float pivotY = relaY / realHeight;
//获取玩家在小地图的中心点位置
this.minimap.rectTransform.pivot = new Vector2(pivotX, pivotY);
this.minimap.rectTransform.localPosition = Vector2.zero;//相对于父物体pivot的子物体pivot位置
this.arrow.transform.eulerAngles = new Vector3(0, 0, -this.playerTransform.eulerAngles.y);
//小地图是2D坐标 标准XYZ 角色是3D坐标 绕Y旋转
}
}