1. 程式人生 > >Unity3d 檢測物體在不在攝像機照射範圍內

Unity3d 檢測物體在不在攝像機照射範圍內

看不懂的把程式碼自己手打一遍就明白了

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 將指令碼掛在攝像機觀察的物體上  物體必須帶有Render
/// </summary>
public class PlayerView : MonoBehaviour {

    bool isRendering;  
    float curtTime = 0f;
    float lastTime = 0f;

    void OnWillRenderObject()
    {
        curtTime = Time.time;
    }
    public bool IsInView(Vector3 worldPos)
    {
        Transform camTransform = Camera.main.transform;
        Vector2 viewPos = Camera.main.WorldToViewportPoint(worldPos);
        Vector3 dir = (worldPos - camTransform.position).normalized;
        float dot = Vector3.Dot(camTransform.forward, dir);     //判斷物體是否在相機前面

        if (dot > 0 && viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1)
            return true;
        else
            return false;
    }

    void Update()
    {
        Vector2 vec2 = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);
        
        if (IsInView(transform.position))   
        {
            Debug.Log("目前本物體在攝像機範圍內");
        }
        else
        {
            Debug.Log("目前本物體不在攝像機範圍內");  
        }
    }
}