Skip to content

Instantly share code, notes, and snippets.

@shanecelis
Last active Nov 10, 2021
Embed
What would you like to do?
A visual element that is draggable.
using UnityEngine;
using UnityEngine.Scripting;
using UnityEngine.UIElements;
/** A visual element that is draggable. Good example of using the
VisualElement's `tranform.position`.
Credit to Crayz for their code:
https://forum.unity.com/threads/creating-draggable-visualelement-and-clamping-it-to-screen.1017715/
*/
public class Draggable : VisualElement {
internal Vector3 offset;
private bool isDragging = false;
public Draggable() {
RegisterCallback<PointerDownEvent>(DragBegin);
RegisterCallback<PointerUpEvent>(DragEnd);
RegisterCallback<PointerLeaveEvent>(DragEndOnLeave);
RegisterCallback<PointerMoveEvent>(PointerMove);
}
public void DragBegin(PointerDownEvent ev) {
isDragging = true;
offset = ev.localPosition;
ev.target.CapturePointer(ev.pointerId);
}
private void DragEnd(PointerUpEvent ev) {
ev.target.ReleasePointer(ev.pointerId);
isDragging = false;
}
private void DragEndOnLeave(PointerLeaveEvent ev) {
ev.target.ReleasePointer(ev.pointerId);
isDragging = false;
}
private void PointerMove(PointerMoveEvent ev) {
if (isDragging) {
Vector3 delta = ev.localPosition - (Vector3) offset;
transform.position = transform.position + delta;
}
}
[Preserve]
public new class UxmlFactory : UxmlFactory<Draggable, UxmlTraits> { }
[Preserve]
public new class UxmlTraits : VisualElement.UxmlTraits { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment