Unity - UGUI - 限制弹出的UI始终保持在屏幕内
📅 2026/7/12 14:11:13
👁️ 阅读次数
📝 编程学习
目的:点击某个物品时,在物品位置弹出信息UI,使UI不会超过屏幕外侧,始终保持在屏幕内
/// <summary> /// 传入ui设置位置的节点rect /// 要求这个节点的rect的height和width决定整个ui的宽高 /// 并且锚点在正中心 /// </summary> /// <param name="targetUIRootRect"></param> /// <param name="followTargetUIPos">目标世界坐标对应的UI坐标</param> void FormatLimitUIInScreen(RectTransform targetUIRootRect, Vector3 followTargetUIPos) { //先将ui的位置设置到目标位置 targetUIRootRect.transform.position = followTargetUIPos; //再修正ui位置到屏幕内 var rectPos = targetUIRootRect.anchoredPosition; if (Mathf.Abs(rectPos.y) + targetUIRootRect.rect.height / 2 > Screen.height / 2) { if (rectPos.y > 0) { rectPos.y = Screen.height / 2 - targetUIRootRect.rect.height / 2; } else { rectPos.y = -Screen.height / 2 + targetUIRootRect.rect.height / 2; } } if (Mathf.Abs(rectPos.x) + targetUIRootRect.rect.width / 2 > Screen.width / 2) { if (rectPos.x > 0) { rectPos.x = Screen.width / 2 - targetUIRootRect.rect.width / 2; } else { rectPos.x = -Screen.width / 2 + targetUIRootRect.rect.width / 2; } } targetUIRootRect.anchoredPosition = rectPos; }
编程学习
技术分享
实战经验