I'm new to the concept of transforming screen coordinates to world coordinates in a 3D world in general, even more so in Unity. I'm using the UnityEngine.EventSystems
library, implementing the IDragHandler
, as I want this to work the same no matter if a mouse or touch input is the source.
I want to drag around a 3D object in world space, locked to one z position. I found this excellent piece of code which I'm now using: http://coffeebreakcodes.com/drag-object-with-mouse-unity3d/
That same code can also be found in the answer here: Drag 3d object using fingers in unity3d
It works exactly as I want it to, apart from one thing: The transformation works fine when the drag starts, but the object makes larger movements than the pointer does, getting worse the further from the object's original position it gets, as if the movement is multiplied with something that gets larger the further away from the original position I get.
This is my code, which is basically the same as in the link above, apart from using the PointerEventData's pointer coordinates instead of Input.mousePosition (a change that did not affect the behaviour):
public class DragInput : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
private Vector3 screenPoint;
private Vector3 offset;
public void OnBeginDrag(PointerEventData eventData)
{
screenPoint = Camera.main.WorldToScreenPoint(transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(eventData.position.x, eventData.position.y, screenPoint.z));
}
public void OnDrag(PointerEventData eventData)
{
Vector3 cursorPoint = new Vector3(eventData.position.x, eventData.position.y, screenPoint.z);
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
transform.position = cursorPosition;
}
public void OnEndDrag(PointerEventData eventData)
{
}
}
EDIT: This video clip showcases the behaviour I'm describing: https://www.dropbox.com/s/qfx2p6kznizft1q/Unity%202017-01-13%2014-32-15-89.avi?dl=0