Movement and zoom in 2d map (time problem)

Hi, I’m making an application for mobile phones, I have a map where you can navigate (moving, zooming in and out), the problem I mention here is that when you zoom in or out (tapping with two fingers) when you finish to do the action and take your fingers out, if you don’t take them both out at the same time, the camera moves (a lot) to another place and it’s really annoying, how do I fix that error? This is the code I use:

    public void cameraController() {
           if (Input.GetMouseButtonDown(0))
        {
            touchStart = cam.ScreenToWorldPoint(Input.mousePosition);
        }
        if (Input.touchCount == 2)
        {
            Touch touchZero = Input.GetTouch(0);
            Touch touchOne = Input.GetTouch(1);

            Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
            Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

            float prevMagnitude = (touchZeroPrevPos - touchOnePrevPos).magnitude;
            float currentMagnitude = (touchZero.position - touchOne.position).magnitude;

            float difference = currentMagnitude - prevMagnitude;
            zoom(difference);
        } else if (Input.GetMouseButton(0))
        {
            Vector3 direction = touchStart - cam.ScreenToWorldPoint(Input.mousePosition);
            Debug.Log("Direction: " + direction);
            Vector3 position = new Vector3(
                Mathf.Clamp(cam.transform.localPosition.x + direction.x * movementSpeed, -124, 173),
                cam.transform.localPosition.y,
                Mathf.Clamp(cam.transform.localPosition.z + direction.z * movementSpeed, -145, 359));
            cam.transform.localPosition = position;
        }
        zoom(Input.GetAxis("Mouse ScrollWheel") * 200f);
        }

Thanks!

You’re mixing and matching touches and mouses. That can be confusing…

Line 19 will show a mouse hit for the remaining finger upon lift.

I like to handle this with a small state machine that once you reach “two fingers touching” status, NOTHING is processed until you reach zero finger status again.

As for mixing / matching touches / mouse, I wrote a MicroTouch class that I use in all my games: it blends mouse and touch and handles it correctly on platform or in editor. You’re welcome to see how it works in my proximity buttons project:

proximity_buttons is presently hosted at these locations:

https://bitbucket.org/kurtdekker/proximity_buttons

https://github.com/kurtdekker/proximity_buttons