Skip to content

Instantly share code, notes, and snippets.

@Leandros

Leandros/main.lua

Last active Jan 22, 2020
Embed
What would you like to do?
Love2D Fixed Timestep
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
@jakebesworth

This comment has been minimized.

Copy link

@jakebesworth jakebesworth commented Apr 30, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.