Hell. I’m having some trouble getting touch drag-to-pan function from working correctly depending on the rotation of the camera’s parent object.
I based the method on this video, which seems to be the closest thing to what I want. I’ve gotten other methods to work, it was hard to keep the objects movement proportional to the amount my finger moved across the screen.
I have the following set up:
I have a camera that is childed to an empty object (at the center of the blue circle) because I want the camera to orbit around this empty object. I then have another empty, the green dot, as a reference point, it’s facing the camera always because it’s childed to the camera.
I have the following script to pan the camera based on the midpoint of where my 2 fingers touched and dragged:
private void Panning() //pans the cart tilt object up to the pan limits.
{
if (Input.touchCount != 2)
return;
if ((Input.GetTouch(0).phase != TouchPhase.Moved && Input.GetTouch(1).phase != TouchPhase.Moved))
return;
if (EventSystem.current.IsPointerOverGameObject(Input.touchCount - 1))
return;
TouchTimer();
Touch touch1 = Input.GetTouch(0);
Touch touch2 = Input.GetTouch(1);
if (Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector3 currentPos = GetWorldPosition((touch1.position + touch2.position)/2);
Vector3 previousPos = GetWorldPosition(((touch1.position - touch1.deltaPosition) + (touch2.position - touch2.deltaPosition)) / 2);
Vector3 difference = currentPos - previousPos;
Vector3 camPos = nonARCamera.transform.localPosition;
camPos += new Vector3(-difference.x * panSensitivity, -difference.y * panSensitivity, 0);
camPos.x = Mathf.Clamp(camPos.x, -panLimit[0], panLimit[1]);
camPos.y = Mathf.Clamp(camPos.y, -panLimit[1], panLimit[1]);
nonARCamera.transform.localPosition = camPos;
}
}
private Vector3 GetWorldPosition(Vector2 _touchPos)
{
Ray rayPos = nonARCamera.ScreenPointToRay(_touchPos);
Plane plane = new Plane(cameraPlaneRef.forward, cameraPlaneRef.position);
float distance;
plane.Raycast(rayPos, out distance);
return rayPos.GetPoint(distance);
}
Basically, every time there is a 2-finger drag, a Plane is created where the green dot reference object is in front of the camera. I then calculate the position of the drag between the current and last frames, and then move the camera’s local position relative to its parent in the opposite direction (making the illusion that the object the camera is look at is moving the same way as the drag).
This works, but only in one direction. If the camera-parent is rotated to the other side of the object, the movement is backwards. If it’s on either side (+/- 90 degrees), nothing happens. I’m not sure what I’m doing wrong here. I know it has to do with the world positions of the current and previous being flipped when you’re behind the target, but I’m not sure how I could rotate the result based on how the camera pivot is rotated.
Any help would be appreciated.