本文主要实现将ui限制在一个范围内,可以是在当前屏幕内,也可以指定区域。
效果图:
上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UITools { public static bool UIAreaLimit(RectTransform target, Rect area, Transform root) { Bounds bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(root, target); Vector2 delta = default; if (bounds.center.x - bounds.extents.x < area.x)//左 { delta.x += Mathf.Abs(bounds.center.x - bounds.extents.x - area.x); } else if (bounds.center.x + bounds.extents.x > area.width / 2)//右 { delta.x -= Mathf.Abs(bounds.center.x + bounds.extents.x - area.width / 2); } if (bounds.center.y - bounds.extents.y < area.y)//上 { delta.y += Mathf.Abs(bounds.center.y - bounds.extents.y - area.y); } else if (bounds.center.y + bounds.extents.y > area.height / 2)//下 { delta.y -= Mathf.Abs(bounds.center.y + bounds.extents.y - area.height / 2); } target.anchoredPosition += delta; return delta != default; } } |
测试脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Test : MonoBehaviour { public RectTransform rt1; private Rect rect; CanvasScaler canvaScaler; void Awake() { canvaScaler = GetComponent<CanvasScaler>(); rect = new Rect(-Screen.width / 2, -Screen.height / 2, Screen.width, Screen.height); float scale = canvaScaler.matchWidthOrHeight == 1 ? canvaScaler.referenceResolution.y / Screen.height : canvaScaler.referenceResolution.x / Screen.width; rect = new Rect(rect.x * scale, rect.y * scale, rect.width * scale, rect.height * scale); } void Update() { UITools.UIAreaLimit(rt1, rect, transform); } } |
- 本文固定链接: http://www.u3d8.com/?p=1964
- 转载请注明: 网虫虫 在 u3d8.com 发表过