0
点赞
收藏
分享

微信扫一扫

Unity-UI和物体可见性的判断方法

判断UI的可见性

    /// <summary>
    /// 判断ui是否能被可见
    /// </summary>
    public bool GetUIVisable(Camera cam, RectTransform ui)
    {
        bool value = true;

        Vector3 pos = Camera.WorldToScreenPoint(ui.position);
        if (pos.z < 0 || pos.x < 0 || pos.x > Screen.width || pos.y < 0 || pos.y > Screen.height)
            value = false;

        return value;
    }

判断物体中心的可见性

    public bool GetObjCenterVisable(Camera cam, Transform obj)
    {
        //转化为视角坐标
        Vector3 viewPos = cam.WorldToViewportPoint(obj.position);

        //  z<0代表在相机背后
        if (viewPos.z < 0)
            return false;

        //  距离farClipPlane太远,摄像机看不到了
        if (viewPos.z > cam.farClipPlane)
            return false;

        //  x,y取值在 0~1之外时代表在视角范围外
        if (viewPos.x < 0 || viewPos.y < 0 || viewPos.x > 1 || viewPos.y > 1)
            return false;

        return true;
    }

判断物体碰撞盒是否在相机视角内

意思就是摄像机范围内可见

    /// <summary>
    /// 相机碰撞盒
    /// </summary>
    private Plane[] _mTempCameraPlanes = new Plane[6];

    private void Update()
    {
        //使用方法;
        print(GetBondsVisable(transform.position, GetComponent<BoxCollider>().size));
    }

    private void LateUpdate()
    {
        //调用Unity的API,获取相机包围盒
        GeometryUtility.CalculateFrustumPlanes(Camera.main, _mTempCameraPlanes);
    }

    /// <summary>
    /// 通过相机包围盒来判定物体是否在视野中。
    /// </summary>
    public bool GetBondsVisable(Vector3 center, Vector3 size)
    {
        Bounds bound = new Bounds(center, size); //这里的Size是半径
        return GeometryUtility.TestPlanesAABB(_mTempCameraPlanes, bound);
    }


以上就是这么多了


感谢您的阅读,如果喜欢,就帮忙点个赞。

点关注,点个关注不迷路哦!!!谢谢






举报

相关推荐

0 条评论