-
Notifications
You must be signed in to change notification settings - Fork 1
/
Timer.lua
87 lines (70 loc) · 1.47 KB
/
Timer.lua
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
local class = require("class")
---@class util.Timer
---@operator call: util.Timer
local Timer = class()
Timer.isPlaying = false
Timer.offset = 0
Timer.rate = 1
Timer.adjustRate = 0.1
---@return number
function Timer:getAbsoluteTime()
return 0
end
---@return number?
function Timer:getAdjustTime() end
---@return number?
function Timer:tryAdjust()
local adjustTime = self:getAdjustTime()
if not adjustTime then
return
end
if adjustTime == self.prevAdjustTime then
return
end
self.prevAdjustTime = adjustTime
return adjustTime
end
---@return number
function Timer:getTime()
if not self.isPlaying then
return self.offset
end
local dt = self:getAbsoluteTime() - self.startTime
local time = dt * self.rate + self.offset
local adjustTime = self:tryAdjust()
if adjustTime and self.adjustRate > 0 then
time = time + (adjustTime - time) * self.adjustRate
self:setTime(time)
end
return time
end
---@param time number
---@return number
function Timer:transform(time)
return time - self:getAbsoluteTime() + self:getTime()
end
---@param time number?
function Timer:setTime(time)
self.offset = time or self:getTime()
self.startTime = self:getAbsoluteTime()
end
---@param rate number
function Timer:setRate(rate)
self:setTime()
self.rate = rate
end
function Timer:pause()
if not self.isPlaying then
return
end
self:setTime()
self.isPlaying = false
end
function Timer:play()
if self.isPlaying then
return
end
self:setTime()
self.isPlaying = true
end
return Timer