I’m currently getting along with the new UIToolkit and I wondering how can I enable a player to “drag” an item from the UI, and as soon as he leaves the “ui element” to have that specific counterpart as game object on his mouse and when he release the button its place on the “Ground”.
If the player doesn’t wanna place it in the Gameworld, he can just move it back to the UI and the action will be canceled.
I know that it can be done via clicking, but how to do with just dragging and dropping?
The reason for dragging is, because I think its a bit faster to just grad it, without having the click or tap action in between, as I would also want to play it on mobile.
For dragging items, I use a combination of
MouseLeaveEvent
MouseMoveEvent
MouseUpEvent
MouseDownEvent
to handle dragging.
private void PositionElement(GameObject objectToPosition)
{
Vector2 pos = Mouse.current.position.ReadValue();
var worldRay = m_Camera.ScreenPointToRay(pos);
RaycastHit hit;
if (Physics.Raycast(worldRay, out hit))
{
objectToPosition.transform.position = hit.point;
}
}
Where m_Camera is a Camera object (I just initialize it to Camera.main on enable)
Do note that the object you want to position should either be filtered out of the raycast or have its collider disabled.