unity3d中检测一个物体是否在摄像机视野范围内

Posted on 2016-07-21 16:19  古水  阅读(3416)  评论(0)    收藏  举报

这个脚本最好是把模型对象的锚点设置在最低点。好了直接上脚本。可以直接复制代码,把CS文件拖到一个Camera上,然后把目标拖到targetTran中去就行了。

using UnityEngine;
using System.Collections;

public class CameraT3 : MonoBehaviour 
{
    // public
    public Transform targetTran;

    // private
    private Rect screenRect;
    private Camera camera;

    void Start ()
    {
        screenRect = new Rect(0, 0, Screen.width, Screen.height);
        camera = GetComponent<Camera>();
    }
    

    void Update ()
    {
        if (screenRect.Contains(camera.WorldToScreenPoint(targetTran.position)))
        {
            Debug.Log("进入摄像机范围!");
        }
        if (!screenRect.Contains(camera.WorldToScreenPoint(targetTran.position)))
        {
            Debug.Log("不在摄像机范围!");
        }
    }
}

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3