Unity学习实现screen space模式下UI跟踪游戏物体(在 UI 中跟踪和显示任何 Gameobject 位置)
Posted 努力码代码走上人生巅峰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity学习实现screen space模式下UI跟踪游戏物体(在 UI 中跟踪和显示任何 Gameobject 位置)相关的知识,希望对你有一定的参考价值。
话不多说,直接上代码:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(CanvasGroup))]
public class UI_Tracking_Target_Pos : MonoBehaviour
//目标物体
public Transform target;
//UI与目标物体的距离
public Vector3 offset;
//当物体不在视图范围内,显示的物体方向图片
public Image targetOrientation;
//要赋值给上面Image的上下左右sprite
public Sprite up_Texture;
public Sprite down_Texture;
public Sprite left_Texture;
public Sprite right_Texture;
//目标物体的屏幕空间坐标
private Vector3 targetScreenPos;
// Update is called once per frame
void Update()
if (!isTargetInView())
transform.GetComponent<CanvasGroup>().alpha = 0;
else
transform.GetComponent<CanvasGroup>().alpha = 1;
targetScreenPos = Camera.main.WorldToScreenPoint(target.position);
transform.GetComponent<RectTransform>().position = targetScreenPos + offset;
private bool isTargetInView()
Vector3 vec = Camera.main.WorldToViewportPoint(target.position);
if (vec.x > 0 && vec.x < 1 && vec.y > 0 && vec.y < 1 && vec.z > 0)
targetOrientation.transform.SetParent(transform);
targetOrientation.transform.position = transform.position;
targetOrientation.transform.GetComponent<CanvasGroup>().alpha = 0;
//物体的中心的在相机内部
return true;
else
targetOrientation.transform.SetParent(transform.parent);
targetOrientation.transform.GetComponent<CanvasGroup>().alpha = 1;
if (vec.x < 0)
targetOrientation.sprite = left_Texture;
targetOrientation.transform.GetComponent<RectTransform>().pivot = new Vector2(0, 0.5f);
targetOrientation.transform.position = new Vector3(0, transform.position.y, 0);
else if (vec.x > 1)
targetOrientation.sprite = right_Texture;
targetOrientation.transform.GetComponent<RectTransform>().pivot = new Vector2(1, 0.5f);
//canvas scale设置为1920*1080
targetOrientation.transform.position = new Vector3(1920, transform.position.y, 0);
else if (vec.y < 0)
targetOrientation.sprite = down_Texture;
targetOrientation.transform.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 0);
targetOrientation.transform.position = new Vector3(transform.position.x, 0, 0);
else if (vec.y > 1)
targetOrientation.sprite = up_Texture;
targetOrientation.transform.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 1);
targetOrientation.transform.position = new Vector3(transform.position.x, 1080, 0);
return false;
Inspector面板配置如下:
效果如下:
以上是关于Unity学习实现screen space模式下UI跟踪游戏物体(在 UI 中跟踪和显示任何 Gameobject 位置)的主要内容,如果未能解决你的问题,请参考以下文章
Unity学习实现screen space模式下UI跟踪游戏物体(在 UI 中跟踪和显示任何 Gameobject 位置)
Unity Shader——夜晚视觉屏幕特效(night vision Screen Effect)
Unity Shaders——屏幕特效混合模式(Blend mode with screen effects)