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!

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;
	}

@VGP117 Steal the camera? :slight_smile: In other words take the camera in the callback method of your choice. Camera c = data.pressEventCamera and then just use that.