Nhận diện cử chỉ (Swipe, Pinch, Tap)
C# Code
using UnityEngine;
using UnityEngine.Events;
public class SwipeInput : MonoBehaviour
{
public UnityEvent OnSwipeLeft, OnSwipeRight, OnSwipeUp, OnSwipeDown;
public UnityEvent<float> OnPinch; // Gửi đi giá trị delta
public UnityEvent OnTap;
private Vector2 touchStartPos;
private Vector2 touchEndPos;
private float minSwipeDistance = 50f;
void Update()
{
// Xử lý Tap & Swipe
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began) {
touchStartPos = touch.position;
}
else if (touch.phase == TouchPhase.Ended) {
touchEndPos = touch.position;
float distance = Vector2.Distance(touchStartPos, touchEndPos);
if (distance < minSwipeDistance) {
OnTap?.Invoke();
} else {
HandleSwipe();
}
}
}
// Xử lý Pinch to Zoom
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;
OnPinch?.Invoke(difference);
}
}
void HandleSwipe()
{
float swipeX = touchEndPos.x - touchStartPos.x;
float swipeY = touchEndPos.y - touchStartPos.y;
if (Mathf.Abs(swipeX) > Mathf.Abs(swipeY)) // Swipe ngang
{
if (swipeX > 0) OnSwipeRight?.Invoke();
else OnSwipeLeft?.Invoke();
}
else // Swipe dọc
{
if (swipeY > 0) OnSwipeUp?.Invoke();
else OnSwipeDown?.Invoke();
}
}
}Một hệ thống để nhận diện các cử chỉ phổ biến trên màn hình cảm ứng như vuốt (swipe), chụm/zoom (pinch), và chạm (tap).