UGUI: How to simply write UI drag and drop effect

code directly

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace Script
{
	class UIDragMover : MonoBehaviour
	{
		public Image Body;//The body of the ui element, panel, etc.
		public RectTransform CanvasRectangle; //The canvas where the image is located
		private bool dragging;
		private Vector2 targetPosition;//The target position when moving
		private Vector2 offset;//Record the offset distance between the mouse and the body before starting to move
		public void Update()
		{
			if (dragging)
			{
				// Move the ui to the target position in units of 0.5 times
				Body.rectTransform.anchoredPosition += (targetPosition - Body.rectTransform.anchoredPosition) * 0.5f;
			}
		}
		public void OnBeginDrag(BaseEventData baseEventData)
		{
			PointerEventData pointerEventData = baseEventData as PointerEventData;
			RectTransformUtility.ScreenPointToLocalPointInRectangle(
				CanvasRectangle, pointerEventData.position, pointerEventData.pressEventCamera, out offset);
			//calculate offset
			offset = Body.rectTransform.anchoredPosition-offset;
			dragging = true;
		}
		public void OnDrag(BaseEventData baseEventData)
		{
			PointerEventData pointerEventData = baseEventData as PointerEventData;
			RectTransformUtility.ScreenPointToLocalPointInRectangle(
				CanvasRectangle, pointerEventData.position, pointerEventData.pressEventCamera, out targetPosition);
			//update target position
			targetPosition = targetPosition + offset;
		}
		public void OnEndDrag(BaseEventData baseEventData)
		{
			dragging = false;
		}
	}
}

How to use it?

First, create a new canvas in Hierarchy, and add the ui components you need to the canvas. Here is an example of panel. Adding a canvas will automatically add an EventSystem


Then drag this script to the Panel, the Body is the object you need to drag and move, in this case it is the panel, and CanvasRectangle is the canvas where the Body is located


Then add the EventTrigger component to the Panel, and add three event types: BeginDrag, Drag, and EndDrag respectively.


Add a callback to each event type, drag the Panel (that is, the ui element of the hanging script) to the 1st position, and select the callback function in the 2nd position


That's it.

Why do you want to move in Update? Yes, you can write this last sentence in OnDrag and delete Update to finish.

Body.rectTransform.anchoredPosition=targetPosition;

But the actual drag will feel stuck, and the gradual movement in Update will increase the sense of smoothness.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324379810&siteId=291194637