hello!
I have written a script witch should zoom the camera in and out by swiping the fingers together on touchscreen. The problem is, that the camera only zooms, then one finger is moving, and the other is fixed. I want only to zoom then both fingers are moving.
Here my Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraZoom : MonoBehaviour {
float previosDistance;
float zoomSpeed = 1.0f;
void Update () {
if (Input.touchCount == 2 &&
(Input.GetTouch (0).phase == TouchPhase.Moved || Input.GetTouch (1).phase == TouchPhase.Began)) {
// recalebrate distance between fingers
previosDistance = Vector2.Distance(Input.GetTouch(0).position, Input.GetTouch(1).position);
} else if (Input.touchCount == 2 &&
(Input.GetTouch (0).phase == TouchPhase.Moved || Input.GetTouch (1).phase == TouchPhase.Moved)) {
float distance;
Vector2 touch1 = Input.GetTouch (0).position;
Vector2 touch2 = Input.GetTouch (1).position;
distance = Vector2.Distance (touch1, touch2);
//Set Camera
float amound = (previosDistance-distance)*zoomSpeed*Time.deltaTime;
// for perpective
// transform.Translate (0, 0, amound);
// for Otrhographic
Camera.main.orthographicSize += amound;
previosDistance = distance;
}
}
}
Your first and second if statement check if touch count is 2 and touch[0].phase is “Moved”. Because your second statement is an “else if”, you will always enter your first “if” statement when your touch[0] has moved, so it makes sense that it only works when that finger is still.
for the easiest implementation, you do not need to care about the touch phases (you cannot rely on them as well).
Just check, if there are exactly two fingers on the screen and then get the screenpositions of them and calculate the pivot point and distance, any youre done. Its nothing more then 4 lines of code for the whole zoom thing.
and? I dont see the problem. My approach is completely independent from what youre trying to accomplish. You can use that code-snippet for every kind of pinch. What you do with “scaleFactor” is up to you.
If you want pixel-perfect pinch, than you just need to map the touch position on to whatever is below the finger-tips.
Thank you but there is the following error while executing
eyNotFoundException: The given key was not present in the dictionary.
System.Collections.Generic.Dictionary`2[System.Int32,UnityEngine.Vector2].get_Item (Int32 key) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150)
CameraZoom.Update () (at Assets/Scripts/CameraZoom.cs:25)
make a debug.log for the fingerId, maybe youre getting something different on your system as I on mine. For me the fingerId is always 0 for the first touchdown and 1 for the next and so on.