Last active
November 10, 2021 06:31
-
-
Save shanecelis/e2f98ac2641c473340e116394c1856bb to your computer and use it in GitHub Desktop.
A visual element that is draggable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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