"real" target-fps calculation

master
Josha von Gizycki 7 years ago
parent 0c87dad736
commit 4988bf7d75

@ -36,8 +36,6 @@
} }
}) })
(aset (:ctx gamestate) "font" "10px monospace")
(defn set-timing (defn set-timing
"sets the current time at the given key" "sets the current time at the given key"
[state timingkey] [state timingkey]
@ -82,6 +80,21 @@
(update-scene) (update-scene)
(set-timing :prev))) (set-timing :prev)))
(defn draw-fps
"draws the current fps"
[gamestate]
(let [ctx (:ctx gamestate)]
(aset ctx "fillStyle" "white")
(.fillRect
ctx
0 0 13 13)
(aset ctx "fillStyle" "black")
(aset ctx "font" "10px monospace")
(.fillText
(:ctx gamestate)
(int (get-in gamestate [:timing :fps]))
0 10)))
(defn draw-step (defn draw-step
"clears the canvas, draws fps and invokes the scene draw function" "clears the canvas, draws fps and invokes the scene draw function"
[gamestate] [gamestate]
@ -93,10 +106,7 @@
scene (scenekey (:scenes gamestate)) scene (scenekey (:scenes gamestate))
drawfunc (:draw scene)] drawfunc (:draw scene)]
(drawfunc gamestate scene)) (drawfunc gamestate scene))
(.fillText (draw-fps gamestate))
(:ctx gamestate)
(int (get-in gamestate [:timing :fps]))
0 10))
(defn mainloop (defn mainloop
"transforms the given gamestate by invoking a series of update "transforms the given gamestate by invoking a series of update
@ -105,11 +115,18 @@
[gamestate] [gamestate]
(let [newstate (update-step gamestate)] (let [newstate (update-step gamestate)]
(draw-step newstate) (draw-step newstate)
; calculate the duration of update-step and draw-step
; substract that from the wait time to reach target-fps
; more accurately
(let [now (get-in newstate [:timing :now])
duration (- (.now js/performance) now)]
(.setTimeout js/window (.setTimeout js/window
(fn [] (fn []
(.requestAnimationFrame js/window (.requestAnimationFrame js/window
#(mainloop newstate))) #(mainloop newstate)))
(/ 1000 (:target-fps gamestate))))) (/
(- 1000 duration)
(:target-fps gamestate))))))
(defn init-scenes (defn init-scenes
"initiates the scene data maps using their respective init functions" "initiates the scene data maps using their respective init functions"

Loading…
Cancel
Save