Unity类原神小地图
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MiniMap : MonoBehaviour { public Transform miniMapRange; private RectTransform rectMap; private RectTransform playerPoint; private RectTransform miniMapMaskRect; public float miniMapRauid; public Transform player; private Vector3 localPos; private Vector3 localRotation; public LayerMask ground; private float mapHalfWeight; private float mapHalfHeight; private float mapMaskHalfWeight; private float mapMaskHalfHeight; private void Awake() { rectMap = transform.Find("Map").GetComponent<RectTransform>(); playerPoint = transform.Find("playerPoint").GetComponent<RectTransform>(); miniMapMaskRect = transform.GetComponent<RectTransform>(); mapHalfWeight = rectMap.sizeDelta.x * 0.5f; mapHalfHeight = rectMap.sizeDelta.y * 0.5f; mapMaskHalfWeight = miniMapMaskRect.sizeDelta.x * 0.5f; mapMaskHalfHeight = miniMapMaskRect.sizeDelta.y * 0.5f; } private void FixedUpdate() { CaculateMiniMapPos(CaculateMapPos()); CaculateplayerPointRotation(); } //世界位置相对地图像素位置 public Vector2 CaculateMapPos() { localPos = miniMapRange.InverseTransformPoint(player.position); localPos = new Vector3(Mathf.Clamp(localPos.x, -1, 1), localPos.y, Mathf.Clamp(localPos.z, -1, 1)); float x = mapHalfWeight * localPos.x + mapHalfWeight; float y = mapHalfHeight * localPos.z + mapHalfHeight; return new Vector2(x,y); } //屏幕像素转换到世界位置 public Vector3 CaculateMapToWorldPos(Vector2 vector2) { Vector3 pos = Vector3.zero; float x = vector2.x / rectMap.sizeDelta.x; float y = vector2.y / rectMap.sizeDelta.y; x -= 0.5f; y -= 0.5f; pos.x = x; pos.z = y; pos.y = 1000; pos= miniMapRange.TransformPoint(pos); if (Physics.Raycast(pos,-Vector3.up,out RaycastHit hit,3000,ground)) { pos.y= hit.point.y; } else pos = Vector3.zero; return pos; } //计算小地图的位置 public void CaculateMiniMapPos(Vector2 pos) { float x = -(pos.x - mapMaskHalfWeight); float y = -(pos.y - mapMaskHalfHeight); rectMap.anchoredPosition = new Vector2(x,y); } //计算地图player旋转 public void CaculateplayerPointRotation() { localRotation = (miniMapRange.rotation * player.rotation).eulerAngles; Vector3 euler = new Vector3(0,0,360- localRotation.y); playerPoint.localRotation = Quaternion.Euler(euler); } }
角色旋转后角色小地图的视野也会跟着旋转。
上方对应世界+z方向
右方对应世界+x方向