zoukankan      html  css  js  c++  java
  • Unity3D UGUI窗口拖拽

    在开发UGUI时

    我们时常需要做一个窗口拖拽的功能

    先上代码

    using UnityEngine;
    using UnityEngine.EventSystems;
    
    public class DragWindow : MonoBehaviour,IPointerDownHandler,IDragHandler
    {
        private Vector2 localMousePos;
        private Vector3 planeLocalPos;
        private RectTransform targetObject;
        private RectTransform parentRectTransform;
        private RectTransform targetRectTransform;
    
        void Awake()
        {
            targetObject = this.transform.GetComponent<RectTransform>();
            if (targetObject == null)
            {
                targetObject = transform as RectTransform;
            }
    
            parentRectTransform = targetObject.parent as RectTransform;
            targetRectTransform = targetObject as RectTransform;
    
        }
    
        public void OnPointerDown(PointerEventData data)
        {
            planeLocalPos = targetRectTransform.localPosition;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRectTransform, data.position, data.pressEventCamera, out localMousePos);
            targetObject.gameObject.transform.SetAsLastSibling();
        }
    
        public void OnDrag(PointerEventData data)
        {
    
            Vector2 localPointerPosition;
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRectTransform, data.position, data.pressEventCamera, out localPointerPosition))
            {
                Vector3 offsetToOriginal = localPointerPosition - localMousePos;
    
                targetObject.localPosition = planeLocalPos + offsetToOriginal;
            }
        }
    }

    使用方法:

    直接将此脚本添加到需要拖拽的窗口就好

    此脚本使用了UGUI内置的事件接口IPointerDownHandler和IDragHandler

    并在接口方法OnPointerDown和OnDrag实现了相应的拖拽逻辑

  • 相关阅读:
    Vscode:代码片段
    【转载】生产力终极指南:用了两年,如今才算真正会用VS Code
    VScode中无法导入自定义模块的问题——搭建虚拟环境
    【Pandas】1.数据读取
    【Pandas】入门案例
    【Pandas】概述
    【Pandas】环境配置
    leetcode多线程题目
    Spring AOP
    MySQL最佳实践
  • 原文地址:https://www.cnblogs.com/fws94/p/8360154.html
Copyright © 2011-2022 走看看