@@ -101,10 +101,13 @@ class Application {
101101 val speed = 0.3
102102 val rs = 20.0
103103 val turnAfter = 5000.0 // seconds
104+ var maxX = sw - rs
105+ val maxY = sh - rs
104106 animation(" rect" , rs) { rect ->
105107 println (" Started new 'rect' coroutine #$index " )
106108 val timer = AnimationTimer ()
107- var turnAt = timer.time + turnAfter
109+ var turnTime = timer.time + turnAfter
110+ val turnTimePhase = turnTime - floor(turnTime / turnAfter) * turnAfter
108111 var vx = speed
109112 var vy = speed
110113 var x = 0.0
@@ -113,19 +116,25 @@ class Application {
113116 val dt = timer.await()
114117 x + = vx * dt
115118 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
120121 vx = - vx
121122 }
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
124133 vy = - vy
125134 }
126135 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
129138 // flip direction
130139 val t = vx
131140 if (random() > 0.5 ) {
@@ -135,8 +144,8 @@ class Application {
135144 vx = - vy
136145 vy = t
137146 }
138- // reset time
139- turnAt = timer.reset() + turnAfter
147+ // reset time, but keep turning time phase
148+ turnTime = ceil( timer.reset() / turnAfter) * turnAfter + turnTimePhase
140149 println (" Delayed #$index for a while at ${timer.time} , resumed and turned" )
141150 }
142151 }
@@ -189,11 +198,18 @@ class AnimationTimer {
189198 val newTime = window.awaitAnimationFrame()
190199 val dt = newTime - time
191200 time = newTime
192- return dt.coerceAtMost(500 .0 ) // at most half a second
201+ return dt.coerceAtMost(200 .0 ) // at most 200ms
193202 }
194203
195204 fun reset (): Double {
196205 time = window.performance.now()
197206 return time
198207 }
208+
209+ suspend fun delay (i : Int ) {
210+ var dt = 0.0
211+ while (dt < i) {
212+ dt + = await()
213+ }
214+ }
199215}
0 commit comments