12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- using UnityEngine;
- public class ZoomImage : MonoBehaviour
- {
- public Transform targetImage;
- public float minScale = 0.5f;
- public float maxScale = 3.0f;
- public float sensitivity = 0.01f;
- private Vector2[] lastTouchPositions = new Vector2[2];
- private float initialDistance;
- private bool isZooming = false;
- private Vector3 initialImagePosition;
- private Vector2 initialTouchPosition;
- void Update()
- {
- HandleZoom();
- HandleMove();
- }
- void HandleZoom()
- {
- if (Input.touchCount == 2)
- {
- Touch touch1 = Input.GetTouch(0);
- Touch touch2 = Input.GetTouch(1);
- if (touch1.phase == TouchPhase.Began || touch2.phase == TouchPhase.Began)
- {
-
- lastTouchPositions[0] = touch1.position;
- lastTouchPositions[1] = touch2.position;
- initialDistance = Vector2.Distance(lastTouchPositions[0], lastTouchPositions[1]);
- isZooming = true;
- }
- else if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved)
- {
-
- Vector2[] currentTouchPositions = new Vector2[2];
- currentTouchPositions[0] = touch1.position;
- currentTouchPositions[1] = touch2.position;
-
- float currentDistance = Vector2.Distance(currentTouchPositions[0], currentTouchPositions[1]);
-
- float scaleFactor = currentDistance / initialDistance;
-
- Vector3 newScale = targetImage.localScale * scaleFactor;
- newScale.x = Mathf.Clamp(newScale.x, minScale, maxScale);
- newScale.y = Mathf.Clamp(newScale.y, minScale, maxScale);
- newScale.z = 1;
- targetImage.localScale = newScale;
-
- initialDistance = currentDistance;
- }
- else if (touch1.phase == TouchPhase.Ended || touch2.phase == TouchPhase.Ended)
- {
- isZooming = false;
- }
- }
- }
- void HandleMove()
- {
- if (Input.touchCount == 1 && !isZooming)
- {
- Touch touch = Input.GetTouch(0);
- if (touch.phase == TouchPhase.Began)
- {
-
- initialTouchPosition = touch.position;
- initialImagePosition = targetImage.position;
- }
- else if (touch.phase == TouchPhase.Moved)
- {
-
- Vector2 touchDelta = touch.position - initialTouchPosition;
-
- Vector3 worldDelta = Camera.main.ScreenToWorldPoint(new Vector3(touchDelta.x, touchDelta.y, 0)) -
- Camera.main.ScreenToWorldPoint(Vector3.zero);
-
- targetImage.position = initialImagePosition + worldDelta;
- }
- }
- }
- }
|