隨筆-Unity中若是物體在相機可視範圍內顯示某物體不然隱藏

若是某個物體離開相機可視範圍則隱藏,若是在範圍內則顯示。。代碼以下ide

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ARGameUI : MonoBehaviour
{
    private GameObject heigetSlide_Button;
    private GameObject searchCueBall;

    public GameObject cueBallPos;

    private void Start()
    {
        heigetSlide_Button = transform.Find("HeightSlide").gameObject;
        searchCueBall = transform.Find("SearchCueBall").gameObject;
        cueBallPos = GameFactory.GetInstance().ballDic[0];
    }

    private void Update()
    {
        if (IsInView(cueBallPos.transform.position))
            searchCueBall.gameObject.SetActive(true);
        else
            searchCueBall.gameObject.SetActive(false);
    }

    /// <summary>
    /// 判斷物體是否在相機視野內
    /// </summary>
    /// <param name="_worldPos">物體的座標</param>
    /// <returns></returns>
    private 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;
    }
}
相關文章
相關標籤/搜索