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