Created
February 15, 2021 10:31
-
-
Save unitycoder/3c8d2a0ee6b1605e372c573fee539c64 to your computer and use it in GitHub Desktop.
mobile zoom and pan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://forum.unity.com/threads/zoom-and-pan-an-image.1048598/#post-6839018 | |
| using System.Collections; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| public class PanZoom : MonoBehaviour { | |
| Vector3 touchStart; | |
| public float zoomOutMin = 1; | |
| public float zoomOutMax = 8; | |
| // Update is called once per frame | |
| void Update () { | |
| if(Input.GetMouseButtonDown(0)){ | |
| touchStart = Camera.main.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 * 0.01f); | |
| }else if(Input.GetMouseButton(0)){ | |
| Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition); | |
| gameObject.transform.position -= direction; | |
| } | |
| zoom(Input.GetAxis("Mouse ScrollWheel")); | |
| } | |
| void zoom(float increment){ | |
| float factor = Mathf.Clamp(gameObject.transform.localScale.x + increment, zoomOutMin, zoomOutMax); | |
| gameObject.transform.localScale = new Vector3(factor, factor, 0); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment