Skip to content

Instantly share code, notes, and snippets.

@shanecelis
Last active November 10, 2021 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanecelis/e2f98ac2641c473340e116394c1856bb to your computer and use it in GitHub Desktop.
Save shanecelis/e2f98ac2641c473340e116394c1856bb to your computer and use it in GitHub Desktop.
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