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; }
标签:moveDistance,isInScreen,移进,ScreenWidthHalf,pos,Unity,sizeDelta,屏幕,rect From: https://www.cnblogs.com/huangzzz/p/16878116.html