-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSwipeDetector.cs
82 lines (72 loc) · 2.41 KB
/
SwipeDetector.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using UnityEngine;
public class SwipeDetector : MonoBehaviour
{
private Vector2 startTouchPosition, endTouchPosition;
private Vector2 startMousePosition, endMousePosition;
private bool isSwiping = false;
public float minSwipeDistance = 50f; // Minimum distance for a swipe to be registered
public float maxSwipeTime = 1f; // Maximum time in seconds for a swipe gesture
private float swipeStartTime;
void Update()
{
// Touch input (for mobile devices)
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
case TouchPhase.Began:
isSwiping = true;
startTouchPosition = touch.position;
swipeStartTime = Time.time;
break;
case TouchPhase.Ended:
if (isSwiping)
{
endTouchPosition = touch.position;
DetectSwipe(startTouchPosition, endTouchPosition);
}
break;
}
}
// Mouse input (for Unity Editor or desktop platforms)
if (Input.GetMouseButtonDown(0))
{
isSwiping = true;
startMousePosition = Input.mousePosition;
swipeStartTime = Time.time;
}
else if (Input.GetMouseButtonUp(0) && isSwiping)
{
endMousePosition = Input.mousePosition;
DetectSwipe(startMousePosition, endMousePosition);
}
}
private void DetectSwipe(Vector2 start, Vector2 end)
{
float swipeDistance = Vector2.Distance(start, end);
float swipeTime = Time.time - swipeStartTime;
if (swipeTime < maxSwipeTime && swipeDistance > minSwipeDistance)
{
Vector2 direction = end - start;
if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y))
{
// Horizontal swipe
if (direction.x > 0)
Debug.Log("Swipe Right");
else
Debug.Log("Swipe Left");
}
else
{
// Vertical swipe
if (direction.y > 0)
Debug.Log("Swipe Up");
else
Debug.Log("Swipe Down");
}
}
// Reset
isSwiping = false;
}
}