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


这个脚本最好是把模型对象的锚点设置在最低点。好了直接上脚本。可以直接复制代码,把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("不在摄像机范围!");
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM