InputProcessor.cs
3.33 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using UnityEngine;
using UnityEngine.EventSystems;
namespace AirFishLab.ScrollingList
{
/// <summary>
/// The class for processing the input value
/// </summary>
public class InputProcessor
{
#region Private Members
/// <summary>
/// The target detecting rect transform
/// </summary>
private readonly RectTransform _rectTransform;
/// <summary>
/// The maximum coordinate of the target rect transform
/// </summary>
private readonly Vector2 _maxRectPos;
/// <summary>
/// The camera which the canvas is referenced
/// </summary>
private readonly Camera _canvasRefCamera;
/// <summary>
/// The time of the last input event
/// </summary>
private float _lastInputTime;
/// <summary>
/// The last input position in the space of the target rect transform
/// </summary>
private Vector2 _lastLocalInputPos;
#endregion
public InputProcessor(RectTransform rectTransform, Camera canvasRefCamera)
{
_rectTransform = rectTransform;
_maxRectPos = _rectTransform.rect.max;
_canvasRefCamera = canvasRefCamera;
}
/// <summary>
/// Get the input information according to the input event data
/// </summary>
public InputInfo GetInputInfo(PointerEventData eventData, InputPhase phase)
{
var deltaPos =
phase == InputPhase.Scrolled
? GetScrollDeltaPos(eventData.scrollDelta)
: GetDeltaPos(eventData.position, phase);
var deltaPosNormalized =
new Vector2(
deltaPos.x / _maxRectPos.x,
deltaPos.y / _maxRectPos.y);
var curTime = Time.realtimeSinceStartup;
if (phase == InputPhase.Began || phase == InputPhase.Scrolled)
_lastInputTime = curTime;
var deltaTime = curTime - _lastInputTime;
_lastInputTime = curTime;
return new InputInfo {
Phase = phase,
DeltaLocalPos = deltaPos,
DeltaLocalPosNormalized = deltaPosNormalized,
DeltaTime = deltaTime
};
}
/// <summary>
/// Get the unit delta pos for the scrolling
/// </summary>
/// <param name="scrollDelta">The original input value</param>
/// <returns>The unit delta pos</returns>
private Vector2 GetScrollDeltaPos(Vector2 scrollDelta)
{
// Ignore the scalar, only return the unit pos and the direction
return scrollDelta.y > 0 ? Vector2.up : Vector2.down;
}
/// <summary>
/// Calculate the local delta position
/// </summary>
private Vector2 GetDeltaPos(Vector2 screenInputPos, InputPhase phase)
{
RectTransformUtility.ScreenPointToLocalPointInRectangle(
_rectTransform, screenInputPos, _canvasRefCamera, out var localPos);
if (phase == InputPhase.Began) {
_lastLocalInputPos = localPos;
return Vector2.zero;
}
var deltaPos = localPos - _lastLocalInputPos;
_lastLocalInputPos = localPos;
return deltaPos;
}
}
}