2D Fixed Step Logic & Linear Interpolated Time Based Movement

Previous topic - Next topic

bigsofty

Not my code (original by Dmitriy Safro) in BB I think.

Converted for those who may need it.

Cheers,


Ian

Code (glbasic) Select
// --------------------------------- //
// Project: Tween
// Start: Monday, November 01, 2010
// IDE Version: 8.148


// SETCURRENTDIR("Media") // seperate media and binaries?

GLOBAL UPDATE_FREQUENCY% = 10 // times per second
GLOBAL update_time# = 1000 / UPDATE_FREQUENCY%
GLOBAL t% , dt% , execution_time% = 0
GLOBAL oldX%, X%

// boucing ball
GLOBAL dirX# = 1

t = GETTIMERALL()
WHILE NOT KEY(1)
dt = GETTIMERALL() - t
t = GETTIMERALL()

execution_time = execution_time + dt

// fixed interval update loop   
        WHILE execution_time >= update_time
Update()
execution_time = execution_time - update_time
WEND

// calculate the remainder FOR motion interpolation
LOCAL et# = execution_time
LOCAL ut# = update_time
LOCAL tween# = et / ut

Render(tween)
WEND

FUNCTION Update:
// time independent speed
LOCAL Speed# = 150.0 / (1000.0 / update_time) // 150.0 pixels per second

// record the old position for tweening
oldX = X

// move the ball
X = X + (Speed * dirX)

// reverse directions if rect is out of screen bounds
IF X < 0 OR X > 640 THEN dirX = - dirX
ENDFUNCTION

FUNCTION Render: tween#
CLEARSCREEN
// interpolate between old and actual positions
LOCAL tx# = X * tween + oldX * (1.0 - tween)

// draw bouncing ball with interpolated values
DRAWRECT tx - 16 , 50 , 32 , 32, RGB(255,0,0)

// draw second bouncing ball WITHOUT tweening
DRAWRECT X - 16 , 200 , 32 , 32, RGB(0,255,0)

SHOWSCREEN
ENDFUNCTION
Cheers,

Ian.

"It is practically impossible to teach good programming style to students that have had prior exposure to BASIC.  As potential programmers, they are mentally mutilated beyond hope of regeneration."
(E. W. Dijkstra)