随笔-Unity中如果物体在相机可视范围内显示某物体否则隐藏

如果某个物体离开相机可视范围则隐藏,如果在范围内则显示。

代码如下:

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;
    }
}

因为是从项目中直接复制出来的,不能直接用。基本功能就是在IsInView(Vector3 wordPos)这个函数内,需要的改吧改吧就可以用了。

猜你喜欢

转载自blog.csdn.net/zhangchong5522/article/details/119385592
今日推荐