January 15, 2021, 06:11:25 PM

### Author Topic: [bmx] Fixed Step Logic & Linear Interpolation by HrdNutz [ 1+ years ago ]  (Read 630 times)

#### BlitzBot

• Jr. Member
• Posts: 1
##### [bmx] Fixed Step Logic & Linear Interpolation by HrdNutz [ 1+ years ago ]
« on: June 29, 2017, 12:28:42 AM »
Title : Fixed Step Logic & Linear Interpolation
Author : HrdNutz
Posted : 1+ years ago

Description : Low frequency update loop combined with motion tweening gives some smooth results

Code :
Code: BlitzMax
1. Graphics(640, 480, 32)
2.
3. Global UPDATE_FREQUENCY = 10 ' times per second
4. Global update_time = 1000 / UPDATE_FREQUENCY
5. Global t , dt , execution_time = 0
6.
7. ' boucing ball
8. Global X# , oldX#
9. Global dirX# = 1
10.
11. t = MilliSecs()
12. While Not KeyDown(KEY_ESCAPE)
13.         dt = MilliSecs() - t
14.         t = MilliSecs()
15.
16.         execution_time:+ dt
17.
18.         ' fixed interval update loop
19.         While execution_time >= update_time
20.                 Update()
21.                 execution_time:- update_time
22.         Wend
23.
24.         ' calculate the remainder for motion interpolation
25.         Local et# = execution_time
26.         Local ut# = update_time
27.         Local tween# = et / ut
28.
29.         Render(tween)
30. Wend
31.
32. Function Update()
33.         ' time independent speed
34.         Local Speed# = 150.0 / (1000.0 / Float(update_time)) ' 150.0 pixels per second
35.
36.         ' record the old position for tweening
37.         oldX = X
38.
39.         ' move the ball
40.         X:+ (Speed * dirX)
41.
42.         ' reverse directions if ball is out of screen bounds
43.         If X < 0 Or X > 640 Then dirX = - dirX
44. End Function
45.
46. Function Render(tween#)
47.         Cls
48.         ' interpolate between old and actual positions
49.         Local tx# = X * tween + OldX * (1.0 - tween)
50.
51.         ' draw bouncing ball with interpolated values
52.         DrawOval tx - 16 , 50 , 32 , 32
53.
54.         ' draw second bouncing ball WITHOUT tweening
55.         DrawOval X - 16 , 200 , 32 , 32
56.
57.         Flip
58. End Function