版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/n_moling/article/details/88823634
首先,百度查到OnBecameVisible和OnBecameInvisible方法,但是该方法在物体被遮挡情况下不适用。
然后就考虑结合遮挡剔除,但是烘焙了多次,不太理想。
找到了InstantOC插件,发现里面用射线检测实现,先说一下该方法的缺点,update随机射线,消耗高,而且必须要有collider才能检测。
相机的检测代码:
namespace LastZero
{
public class CameraDetection: MonoBehaviour {
public LayerMask layerMsk;
public int samples;
public int hideDelay;
public float viewDistance;
private RaycastHit hit;
private Ray ray;
private DetectionTarget target;
private void Awake()
{
hit = new RaycastHit();
GetComponent<Camera>().farClipPlane = viewDistance;
}
private void Update()
{
for (int k = 0; k <= samples; k++)
{
ray = GetComponent<Camera>().ScreenPointToRay(new Vector3(Random.Range(0, Screen.width), Random.Range(0, Screen.height), 0f));
if (Physics.Raycast(ray, out hit, viewDistance, layerMsk.value))
{
if (target = hit.transform.GetComponent<DetectionTarget>())
{
target.SetShow(hideDelay);
}
}
}
}
}
}
物体自我处理逻辑:
namespace LastZero
{
public class DetectionTarget: MonoBehaviour {
private Renderer[] renders;
private bool isShow;
private float hideDelay;
private void Awake()
{
renders = GetComponentsInChildren<Renderer>();
}
private void Update()
{
if (isShow)
{
hideDelay--;
if (hideDelay < 0)
{
SetHide();
}
}
else
{
SetEnable(false);
}
}
public void SetShow(int delay)
{
hideDelay = delay;
isShow = true;
SetEnable(true);
}
private void SetHide()
{
isShow = false;
}
private void SetEnable(bool b)
{
for (int i = 0; i < renders.Length; i++)
{
renders[i].enabled = b;
}
}
private void OnBecameVisible()
{
Debug.Log("OnBecameVisible");
}
private void OnBecameInvisible()
{
Debug.Log("OnBecameInvisible");
}
}
}