ps:刚好项目要实现这个功能,翻了翻网上没有找到相关文章,自己就写了一个,有什么更好的建议还请多指教
实现思路:
1、检测物体是否移出屏幕外
这部分unity有现成API,OnBecameVisible,与OnBecameInvisible. 这两个函数可以检测,但脚本要挂在检测的物体上,物体要有render组件
2、确定ui边缘位置
物体世界坐标转为屏幕左边,计算屏幕中心点与物体屏幕坐标连线,与屏幕边缘相交的点.
3、判断与屏幕相交的线是哪一条
使用矩阵给目标物体建立新的坐标
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BeameF : MonoBehaviour
{
//参照的摄像机
GameObject m_camera;
//目标名称
string m_objName;
//提示按钮是否出现
bool m_isButtonDis = false;
//提示按钮
public GameObject m_Button0;
//提示ui状态
public enum Disstate
{
Left,
Right,
Up,
Down
}
Disstate m_dis;
void Start()
{
m_camera = GameObject.FindGameObjectWithTag("MainCamera");
}
void OnBecameVisible()
{
//提示按钮没有出现
m_isButtonDis = false;
Debug.Log(this.name + "+" + "Visible");
//关闭按钮提示
m_objName = this.name;
InterativeButtonCueClose(m_objName);
}
void OnBecameInvisible()
{
Debug.Log(this.name + "+" + "Invisible");
//目标坐标转屏幕坐标
Vector2 objScreen = Camera.main.WorldToScreenPoint(this.transform.position);
//屏幕中心点与屏幕边缘的交点
Vector3 point = Point(objScreen);
//摄像机位置下目标位置
Vector3 m_targetV3 = CalUVByMatrix(MakeMatrix(this.transform.position, m_camera.transform.forward, m_camera.transform.up, m_camera.transform.right), m_camera.transform.position);
//打开按钮提示
m_objName = this.name;
InterativeButtonCue(m_objName, m_targetV3, point);
//提示按钮出现
m_isButtonDis = true;
}
void Update()
{
if (m_isButtonDis)
{
StartCoroutine(Detection());
}
else
{
//关闭按钮提示
m_objName = this.name;
InterativeButtonCueClose(m_objName);
}
}
//协程减少检测频率
IEnum