Unity 判断UI对象是否在屏幕内,并且把对象移进屏幕

  public static bool JudgmentUiInScreen(GameObject obj)
    {
        RectTransform rect = obj.GetComponent<RectTransform>();
        RectTransform uiRoot = rect.root.GetComponent<RectTransform>();
        Vector2 pivotVec = rect.pivot;
        Vector3 pos = uiRoot.InverseTransformPoint(obj.transform.position); //取得当前UI在屏幕当中的位置
        float upY, downY, leftX, rightX;
        downY = pos.y - rect.sizeDelta.y * pivotVec.y;
        upY = pos.y + rect.sizeDelta.y * (1 - pivotVec.y);
        leftX = pos.x - rect.sizeDelta.x * pivotVec.x;
        rightX = pos.x + rect.sizeDelta.x * (1 - pivotVec.x);
        Vector3 moveDistance = new Vector3(0, 0,0);
        int offset = 50;
        //判断当前的位置 与屏幕坐标的关系
        bool isInScreen = true;
        
        float ScreenWidthHalf = uiRoot.sizeDelta.x /2;
        float ScreenHeightHalf = uiRoot.sizeDelta.y /2;
        if (rightX > ScreenWidthHalf)
        {
            isInScreen = false;
            moveDistance.x = ScreenWidthHalf - rightX - offset;
        }
        else if (leftX < - ScreenWidthHalf)
        {
            isInScreen = false;
            moveDistance.x = -ScreenWidthHalf - leftX + offset;
        }

        if (upY > ScreenHeightHalf)
        {
            isInScreen = false;
            moveDistance.y = ScreenHeightHalf - upY - offset;
        }
        else if (downY < -ScreenHeightHalf)
        {
            isInScreen = false;
            moveDistance.y = -ScreenHeightHalf - downY + offset;
        }
        moveDistance.x = moveDistance.x + pos.x;
        moveDistance.y = moveDistance.y + pos.y;
        RectTransform parentRectTransform = rect.parent.GetComponent<RectTransform>();
        rect.transform.position =  uiRoot.TransformPoint(moveDistance); 
        //GameDebug.Log($"----------JudgmentUiInScreen ,[{isInScreen}],[{moveDistance}] ,[{ScreenWidthHalf}],[{ScreenHeightHalf}]");
        return isInScreen;
    }

  

posted @ 2022-11-10 19:16  姿态H  阅读(744)  评论(0编辑  收藏  举报