如何使用光线投射检测我在屏幕上看到的对象?

How can I detect an object that I see on screen using Raycasting?

所以,我想检查一下我是否在屏幕上看到了一个对象。当然是使用光线投射。

代码:

private void SeeObject(){
  ISeeObj = false;
  if (Vector3.Dot(cam.transform.forward, (cam.transform.position - obj.transform.position).normalized) < -0.65f){
    RaycastHit hit;
    if (Physics.Raycast(cam.transform.position, (obj.transform.position - cam.transform.position).normalized, out hit, range, layerMask)){
      if (hit.transform.name == obj.name){
        ISeeObj = true;
        Debug.Log("I see an Object");
      }
    }
  }
}

我也试过使用

if (Vector3.Dot(cam.transform.forward,
(cam.transform.position - obj.transform.position).normalized) > 0 )

但是没用。

我建议不要为此使用Raycast


MonoBehaviour 已经实现了两个方法 OnBecameVisible

OnBecameVisible is called when the renderer became visible by any camera.

This message is sent to all scripts attached to the renderer.

OnBecameInvisible

OnBecameInvisible is called when the renderer is no longer visible by any camera.

This message is sent to all scripts attached to the renderer.

(两者也可以是协程)


因此,如果您需要不断检查某个对象当前是否可见,请附加一个组件,例如

public class VisibilityChecker : MonoBehaviour
{
    // E.g. using a read-only auto-property
    public bool IsVisible{ get; private set; }

    // If you rather like to be able to also see the value in the Inspector for debugging use
    //public bool IsVisible { get { return _isVisible;}}
    //[SerializeField] private bool _isVisible;

    private void OnBecameVisible()
    {
        IsVisible = true;

        //or
        //_isVisible = true;
    }

    private void OnBecameInvisible()
    {
        IsVisible = false;

        //or
        //_isVisible = false;
    }
}

并且在另一个脚本中,例如在Update中检查它喜欢

private VisibilityChecker objVisibilityChecker;

private void Awake()
{
    objVisibilityChecker = obj.GetComponent<VisibilityChecker>();
}

private void Update()
{
    if(objVisibilityChecker.IsVisible)
    {
        // Do something
    }
    else
    {
        // Do another thing
    }
}