【Unity】实现小地图
目录
- 一、前言
- 二、思路
- 三、具体步骤
- 1、创建一个顶视角摄像机Camera
- 2、创建Render Texture
- 3、Render Texture赋值给顶视角摄像机的Target Texture
- 4、使用Raw Image显示
- 5、将RenderTexture赋值给RawImage的Texture属性
- 四、运行效果
- 五、进阶
一、前言
小地图功能在很多游戏中都有,特别是RPG游戏,这篇文章介绍小地图的功能实现。
二、思路
专门创建一个顶视角的摄像机,然后摄像机有个Target Texture属性,可以将渲染的图形输出到Render Texture中,我们使用UGUI的Raw Image来显示这张Render Texture即可。
三、具体步骤
1、创建一个顶视角摄像机Camera
在需要显示小地图的场景中 创建一个Camera,保留原有的主摄像机 Main Camera
2、创建Render Texture
创建Render Texture
3、Render Texture赋值给顶视角摄像机的Target Texture
4、使用Raw Image显示
在Canvas中 创建一个RawImage
5、将RenderTexture赋值给RawImage的Texture属性
四、运行效果
运行Unity效果如下
参考文档:教你3个步骤实现Unity小地图(知识点:RenderTexture、Mask、shader)
五、进阶
1、功能需求:在已知场景大小的条件下,通过调整 小地图Camera位置 和 orthographicSize值 使得场景居中显示在RawImage中。同时,使用ui图片Image代替 某个物体(如玩家) 显示在RawImage上,随着物体的移动,ui图片在RawImage上按照一定的比例移动。
注:小地图Camera位置 和 orthographicSize值 在初始化时调整,只调整一次,小地图Camera不随着玩家移动而移动。
using UnityEngine;
using UnityEngine.UI;public class MiniMapController : MonoBehaviour
{[Header("小地图设置")]public Camera miniMapCamera;// 小地图专用摄像机public RawImage miniMapRawImage;// 显示小地图的RawImagepublic RectTransform miniMapRect;public RectTransform playerIcon;// 代表玩家的UI图片public Transform playerTransform;// 实际玩家物体[Header("显示设置")][Range(0.1f, 1f)] public float padding = 0.95f; // 边距比例Vector2 sceneSize = new Vector2(100,100);// 2D场景大小private void Start(){miniMapRect = miniMapRawImage.GetComponent<RectTransform>();// 确保小地图摄像机是正交投影miniMapCamera.orthographic = true;// 计算摄像机高度(确保完整看到场景)float aspectRatio = miniMapRect.rect.width / miniMapRect.rect.height;float sceneRatio = sceneSize.x / sceneSize.y;// 根据宽高比调整正交大小if (aspectRatio > sceneRatio){// 以高度为准miniMapCamera.orthographicSize = (sceneSize.y / 2) / padding;}else{// 以宽度为准miniMapCamera.orthographicSize = (sceneSize.x / aspectRatio / 2) / padding;}// 设置摄像机位置(在场景正上方)miniMapCamera.transform.position = new Vector3(sceneSize.x / 2,sceneSize.y / 2,miniMapCamera.transform.position.z);}private void Update(){if (playerTransform == null || playerIcon == null) return;// 将玩家的世界坐标转换为小地图摄像机的视口坐标 (0-1范围)Vector3 viewportPos = miniMapCamera.WorldToViewportPoint(playerTransform.position);// 将视口坐标转换为UI坐标Vector2 uiPos = new Vector2(viewportPos.x * miniMapRect.rect.width - miniMapRect.rect.width / 2,viewportPos.y * miniMapRect.rect.height - miniMapRect.rect.height / 2);// 设置玩家图标位置playerIcon.anchoredPosition = uiPos;}}
2、功能需求:小地图Camera跟随玩家移动
using UnityEngine;/// <summary>
/// 小地图摄像机跟随
/// Auhor: linxinfa
/// </summary>
public class MiniMapCameraFollow : MonoBehaviour
{public Transform playerTransform;/// <summary>/// 高度/// </summary>public float distanceUp = 1.3f;private Transform miniMapCameraTransform;void Awake(){miniMapCameraTransform = transform;}void LateUpdate(){if (playerTransform == null) return;miniMapCameraTransform.position = playerTransform.position + Vector3.up * distanceUp; }
}