-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSwipeHandler.cs
More file actions
77 lines (63 loc) · 1.82 KB
/
SwipeHandler.cs
File metadata and controls
77 lines (63 loc) · 1.82 KB
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
using UnityEngine;
using System.Collections;
namespace Snake
{
public class SwipeHandler : UserInputHandler
{
private float screenDiagonalSize;
private float minimumSwipeDistanceInPixels;
private bool touchStarted;
private Vector2 touchStartPosition;
public float minSwipeDistance = 0.04f;
[PostConstruct]
public void Initialize ()
{
screenDiagonalSize = Mathf.Sqrt (Screen.width * Screen.width + Screen.height * Screen.height);
minimumSwipeDistanceInPixels = minSwipeDistance * screenDiagonalSize;
}
public override void HandleInput ()
{
if (Input.touchCount > 0)
{
var touch = Input.touches [0];
switch (touch.phase)
{
case TouchPhase.Began:
touchStarted = true;
touchStartPosition = touch.position;
break;
case TouchPhase.Ended:
if (touchStarted)
{
HandleSwipe (touch);
touchStarted = false;
}
break;
case TouchPhase.Canceled:
touchStarted = false;
break;
}
}
}
private void HandleSwipe (Touch touch)
{
Vector2 lastPosition = touch.position;
float distance = Vector2.Distance (lastPosition, touchStartPosition);
if (distance > minimumSwipeDistanceInPixels)
{
float dy = lastPosition.y - touchStartPosition.y;
float dx = lastPosition.x - touchStartPosition.x;
float angle = Mathf.Rad2Deg * Mathf.Atan2 (dx, dy);
angle = (360 + angle - 45) % 360;
if (angle < 90)
Handle (Direction.Right);
else if (angle < 180)
Handle (Direction.Down);
else if (angle < 270)
Handle (Direction.Left);
else
Handle (Direction.Up);
}
}
}
}