i want the camera 1) focus on the middle point of two finger touch-point when zoom in/out. 2) rotate around focused object with two finger rotate.
what’s the best way to do it?
TIA!
For all methods, you’ll need to store/access the old touchpositions from the previous frame. Also, raycast into the scene through (touchpoint1.screenposition+touchpoint2.screenposition)/2 to find your center of reference.
Scale (implemented as a translation of your camera’s position towards/away from the center of reference):
- Compute the difference of Distance(touchpoint1.screenposition,touchpoint2.screenposition) and Distance(oldtouchpoint1.screenposition,oldtouchpoint2.screenposition) to find out how much you want to zoom in/out. The resulting zoom seems more intuitive if you use the difference, as opposed to the quotient.
- Compute the direction cam2reference=centerOfReference-camera.transform.position;
- Add cam2referencetouchdifferencescaleSpeedFactor*Time.deltaTime to your camera’s position each frame
Rotation (implemented as a rotation of your camera around the center of reference):
- Compute the angular difference between the two old and new touch points (see below)
- Use camera.RotateAround(centerOfReference,Vector3.up,angularDiffrotateSpeedFactorTime.deltaTime) each frame
Some example code that works for me (although it might be possible to make this simpler using some of the convenience functions Unity provides):
// get angular difference
float angleNow = Mathf.Atan2(touchpoint1.screenPosition.y - touchpoint2.screenPosition.y, touchpoint1.screenPosition.x - touchpoint2.screenPosition.x) * Mathf.Rad2Deg;
float angleThen = Mathf.Atan2(oldtouchpoint1.y - oldtouchpoint2.y, oldtouchpoint1.x - oldtouchpoint2.x) * Mathf.Rad2Deg;
// wraparound failsafes (wraparound of Mathf.Atan2 is at +-180)
if(angleNow>90&&angleThen<-90)
angleNow-=360;
if(angleNow<-90&&angleThen>90)
angleNow+=360;
angularDiff = angleNow - angleThen;