@@ -101,10 +101,13 @@ class Application {
101
101
val speed = 0.3
102
102
val rs = 20.0
103
103
val turnAfter = 5000.0 // seconds
104
+ var maxX = sw - rs
105
+ val maxY = sh - rs
104
106
animation(" rect" , rs) { rect ->
105
107
println (" Started new 'rect' coroutine #$index " )
106
108
val timer = AnimationTimer ()
107
- var turnAt = timer.time + turnAfter
109
+ var turnTime = timer.time + turnAfter
110
+ val turnTimePhase = turnTime - floor(turnTime / turnAfter) * turnAfter
108
111
var vx = speed
109
112
var vy = speed
110
113
var x = 0.0
@@ -113,19 +116,25 @@ class Application {
113
116
val dt = timer.await()
114
117
x + = vx * dt
115
118
y + = vy * dt
116
- val xRange = 0.0 .. sw - rs
117
- val yRange = 0.0 .. sh - rs
118
- if (x !in xRange ) {
119
- x = x.coerceIn(xRange)
119
+ if (x > maxX) {
120
+ x = 2 * maxX - x
120
121
vx = - vx
121
122
}
122
- if (y !in yRange) {
123
- y = y.coerceIn(yRange)
123
+ if (x < 0 ) {
124
+ x = - x
125
+ vx = - vx
126
+ }
127
+ if (y > maxY) {
128
+ y = 2 * maxY - y
129
+ vy = - vy
130
+ }
131
+ if (y < 0 ) {
132
+ y = - y
124
133
vy = - vy
125
134
}
126
135
rect.setPosition(x, y)
127
- if (timer.time >= turnAt ) {
128
- delay(1000 ) // pause a bit
136
+ if (timer.time >= turnTime ) {
137
+ timer. delay(1000 ) // pause a bit
129
138
// flip direction
130
139
val t = vx
131
140
if (random() > 0.5 ) {
@@ -135,8 +144,8 @@ class Application {
135
144
vx = - vy
136
145
vy = t
137
146
}
138
- // reset time
139
- turnAt = timer.reset() + turnAfter
147
+ // reset time, but keep turning time phase
148
+ turnTime = ceil( timer.reset() / turnAfter) * turnAfter + turnTimePhase
140
149
println (" Delayed #$index for a while at ${timer.time} , resumed and turned" )
141
150
}
142
151
}
@@ -189,11 +198,18 @@ class AnimationTimer {
189
198
val newTime = window.awaitAnimationFrame()
190
199
val dt = newTime - time
191
200
time = newTime
192
- return dt.coerceAtMost(500 .0 ) // at most half a second
201
+ return dt.coerceAtMost(200 .0 ) // at most 200ms
193
202
}
194
203
195
204
fun reset (): Double {
196
205
time = window.performance.now()
197
206
return time
198
207
}
208
+
209
+ suspend fun delay (i : Int ) {
210
+ var dt = 0.0
211
+ while (dt < i) {
212
+ dt + = await()
213
+ }
214
+ }
199
215
}
0 commit comments