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

 

转载于:https://my.oschina.net/u/3184885/blog/1560384

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值