How to apply: Mount the following script on a UI picture that requires drag-and-drop functionality
Two kinds of drag-and-drop selection: A. Center Drag (Image Center following mouse position) m_isprecision to false;
B. Precise drag and drop (picture is mouse click position follow mouse position) m_isprecision is true;
1 /*************************************************2 * Project name: Ugui General3 * Script Creator: Magic card4 * Script creation time: 2017.12.145 * Script function: UI picture dragging function (Attach script to picture that need to drag and drop)6 * ***********************************************/7 usingUnityengine;8 usingSystem.Collections;9 usingUnityengine.eventsystems;Ten One //UI Picture Drag function class A Public classUidragbymocha:monobehaviour,ibegindraghandler, Idraghandler, Ienddraghandler - { -[Header ("whether the precise drag")] the Public BOOLm_isprecision; - - //stores the offset between the center point of the picture and the mouse click Point - PrivateVector3 M_offset; + - //Recttransform component that stores the currently dragged picture + Privaterecttransform M_rt; A voidStart () at { - //Initialize -M_rt= gameobject.getcomponent<recttransform>(); - } - - //start dragging trigger in Public voidOnbegindrag (pointereventdata eventData) - { to //Calculate offset operation if exact drag + if(m_isprecision) - { the //mouse coordinates when storing a click * Vector3 Tworldpos; $ //UI screen coordinates converted to world coordinatesPanax NotoginsengRecttransformutility.screenpointtoworldpointinrectangle (M_rt, eventdata.position, EventData.pressEventCamera, outtworldpos); - //Calculate offset theM_offset = transform.position-Tworldpos; + } A //Otherwise, the default offset is 0 the Else + { -M_offset =Vector3.zero; $ } $ - setdraggedposition (eventData); - } the - //Trigger during draggingWuyi Public voidOndrag (pointereventdata eventData) the { - setdraggedposition (eventData); Wu } - About //End Drag Trigger $ Public voidOnenddrag (pointereventdata eventData) - { - setdraggedposition (eventData); - } A + /// <summary> the ///Set Picture Position method - /// </summary> $ /// <param name= "EventData" ></param> the Private voidsetdraggedposition (pointereventdata eventData) the { the //stores the current mouse location the Vector3 Globalmousepos; - //UI screen coordinates converted to world coordinates in if(Recttransformutility.screenpointtoworldpointinrectangle (M_rt, eventdata.position, EventData.pressEventCamera, outglobalmousepos)) the { the //set position and offset AboutM_rt.position = Globalmousepos +M_offset; the } the } the}
About Ugui pictures in unity drag and drop function