Last active
April 24, 2024 20:38
-
-
Save Leandros/98624b9b9d9d26df18c4 to your computer and use it in GitHub Desktop.
Love2D Fixed Timestep
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local TICKRATE = 1/60 | |
function love.update(dt) | |
end | |
function love.draw(dt) | |
end | |
function love.run() | |
if love.math then | |
love.math.setRandomSeed(os.time()) | |
end | |
if love.load then love.load(arg) end | |
local previous = love.timer.getTime() | |
local lag = 0.0 | |
while true do | |
local current = love.timer.getTime() | |
local elapsed = current - previous | |
previous = current | |
lag = lag + elapsed | |
if love.event then | |
love.event.pump() | |
for name, a,b,c,d,e,f in love.event.poll() do | |
if name == "quit" then | |
if not love.quit or not love.quit() then | |
return a | |
end | |
end | |
love.handlers[name](a,b,c,d,e,f) | |
end | |
end | |
while lag >= TICKRATE do | |
if love.update then love.update(TICKRATE) end | |
lag = lag - TICKRATE | |
end | |
if love.graphics and love.graphics.isActive() then | |
love.graphics.clear(love.graphics.getBackgroundColor()) | |
love.graphics.origin() | |
if love.draw then love.draw(lag / TICKRATE) end | |
love.graphics.present() | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great job Leandros!
I also stumbled across: https://gafferongames.com/post/fix_your_timestep/
And your post: https://www.reddit.com/r/love2d/comments/47v1b6/little_thing_i_made_to_add_fixed_timestep/d0gs76g/
The goal being trying to get constant game tick rate, and variable frame rate (such as users with vsync, or disabling, but having same game experience, or custom FPS cap).
I noticed that your current code differs from 11.X sample here: https://love2d.org/wiki/love.run
I noticed this because your code doesn't work with: https://love2d.org/wiki/love.timer.getFPS Fixed by using love.timer.step()
I took the liberty of converting your version to 11.X:
The updated code is available here: https://gist.github.com/jakebesworth/ac09d54cc05690250096f977105a41f8
Also there was some nice discussion about it here: https://love2d.org/forums/viewtopic.php?f=3&t=85166&start=10 where I added a "spiral of death" fix or otherwise mentioned near the end of the Fix your Timestep article (if simulation takes longer than tick rate)
Last issue was Licensing, it'd be nice if you could provide a license for this. For my updated version, assuming I consider it a forked gist, would be MIT 2018