Drag UI by touch
The Scrollrect works horribly with multitouch so I want to do my own solution.
I got this code from unity learn-page:
public void OnPointerDown (PointerEventData data) {
RectTransformUtility.ScreenPointToLocalPointInRectangle (panelRectTransform, data.position, data.pressEventCamera, out pointerOffset);
pointerOffset = pointerOffset * panelRectTransform.localScale.x;
}
public void OnDrag (PointerEventData data) {
if (panelRectTransform == null)
return;
Vector2 localPointerPosition;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle (
canvasRectTransform, data.position, data.pressEventCamera, out localPointerPosition
)) {
panelRectTransform.localPosition = localPointerPosition - pointerOffset;
}
}
I got it almost working by replacing data.position with Input.GetTouch(0).position, but the pointerOffset is always wrong because setting any camera instead of data.pressEventCamera doesn't work.
So the question is what can I put into the RectTransformUtility instead of data.pressEventCamera?
Thanks for answering!
Answer by VGP117 · Sep 14, 2015 at 09:31 AM
Thanks for the answer. But I've already done my own solution for RectTransformUtility.ScreenPointToLocalPointInRectangle too.
For anyone wondering here is my new code:
public void OnPointerDown (PointerEventData data)
{
mouseOffset = GetPointerOffSet (panelRectTransform, data.position);
}
public void OnDrag (PointerEventData data)
{
panelRectTransform.localPosition = GetCenteredPointerPos (data.position) - mouseOffset;
}
Vector2 GetPointerOffSet (RectTransform rt, Vector2 pointerPos)
{
Vector2 centeredPointerPos = (GetCenteredPointerPos (pointerPos));
Vector2 offSet = centeredPointerPos - (Vector2)rt.localPosition;
return offSet;
}
Vector2 GetCenteredPointerPos (Vector2 pointerPos)
{
Vector2 centeredPointerPos = new Vector2 (pointerPos.x - Screen.width / 2f, pointerPos.y - Screen.height / 2f);
centeredPointerPos /= canvasRectTransform.localScale.x;
return centeredPointerPos;
}
Your answer
Follow this Question
Related Questions
To use touch & raycasting to *drag and drop* a game object... 1 Answer
How to detect the touch on certain Game Object (UI Panel) 1 Answer
Weapon arsenal Inventory UI 0 Answers
How to interact with UI elements and oculus touch controller? (No Gaze!) 3 Answers
Help with ui scaling on screens with different aspect ratios. -3 Answers