summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Thompson <dthompson2@worcester.edu>2013-07-31 22:47:35 -0400
committerDavid Thompson <dthompson2@worcester.edu>2013-07-31 22:47:35 -0400
commitaf6bf9d960b0135d960c195c67a0f5fa34e9d656 (patch)
tree5bc577db94cd5f52c65d6f714f250ac5d4ce9830
parent2a7602eb06b7ec78efcec10e283a7a71e995f8a3 (diff)
Improve game loop.
Instead of a busy loop that eats all of the CPU, sleep in-between frames when possible.
-rw-r--r--2d/game-loop.scm34
1 files changed, 16 insertions, 18 deletions
diff --git a/2d/game-loop.scm b/2d/game-loop.scm
index 8352fdd..d8554db 100644
--- a/2d/game-loop.scm
+++ b/2d/game-loop.scm
@@ -137,32 +137,30 @@ is the unused accumulator time."
(update (- accumulator frame-interval)))
accumulator))
+(define (time-left current-time next-time)
+ (max (floor (- next-time (SDL:get-ticks))) 0))
+
;;;
;;; Game Loop
;;;
(define (run-game-loop)
"Runs event handling, update, and render loop."
- (define (game-loop time last-time fps-time accumulator fps)
+ (define (game-loop last-time next-time fps-time accumulator fps)
(handle-events)
- (let* ((dt (- time last-time))
+ (let* ((time (SDL:get-ticks))
+ (dt (- time last-time))
(accumulator (+ accumulator dt))
(current-fps-time (+ fps-time dt))
- (current-time (SDL:get-ticks)))
- ;; Update and render when the accumulator reaches the threshold.
- (if (>= accumulator frame-interval)
- (let ((remainder (update accumulator)))
- (render)
- (game-loop current-time
- time
- (modulo current-fps-time 1000)
- remainder
- (increment-fps fps current-fps-time)))
- (game-loop current-time
- time
- current-fps-time
- accumulator
- fps))))
+ (remainder (update accumulator)))
+ (render)
+ ;; Sleep for a bit if there's time in between frames
+ (SDL:delay (time-left (SDL:get-ticks) next-time))
+ (game-loop time
+ (+ next-time frame-interval)
+ (modulo current-fps-time 1000)
+ remainder
+ (increment-fps fps current-fps-time))))
(let ((time (SDL:get-ticks)))
- (game-loop time time 0 0 0)))
+ (game-loop time (+ time frame-interval) 0 0 0)))