UGUI 限制UI在屏幕内移动

该博客介绍了如何在Unity3D中使用UGUI系统,使UI元素能够跟随鼠标移动,并在超出屏幕边界时自动调整位置,保持在屏幕范围内。提供了一个演示工程作为参考。
摘要由CSDN通过智能技术生成

实现功能:ui物体跟随鼠标移动,当ui超出屏幕的时候,自动适配到屏幕内。

在这里插入代码片
//ui显示的方位
   public enum Orientation
    {
   
        LeftDown = 0,
        LeftUp,
        LeftCenter,
        RightUp,
        RigthDown,
        RightCenter,
        CenterUp,
        CenterDown,
        Center
    }

    public class ScreenLimit : MonoBehaviour
    {
   
        [Tooltip("物体方位")]
        public Orientation m_ori;
        [Tooltip("限制在屏幕内的物体")]
        public RectTransform target;
        [Tooltip("出现的位置相对于手指点击位置的偏移量")]
        public float m_posOffset = 55f;

        public CanvasScaler canvasScaler;

        private bool _isbuttonDown = false;


        private void Update()
        {
   
            if (Input.GetMouseButtonDown(0))
            {
   
                _isbuttonDown = true;
            }
            else if (Input.GetMouseButtonUp(0))
            {
   
                _isbuttonDown = false;
            }
            if (_isbuttonDown)
            {
   
                SetUIPos();
            }
        }

        /// <summary>
        /// 根据位置信息,设置不同方位的偏移量
        /// </summary>
        public void SetUIPos()
        {
   
            Vector2 curInputPos = Input.mousePosition;
            float x = curInputPos.x;
            float y = curInputPos.y;
            float w = Mathf.Abs(target.rect.x) * GetScaleFactor<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值