Page 2 of 2

Re: sleep() in default love.run

Posted: Fri Aug 26, 2011 6:52 pm
by chrism
Thanks for the run() example, much better than the way I was limiting FPS.

Re: sleep() in default love.run

Posted: Sun Aug 28, 2011 5:54 pm
by Rad3k
Ok, here is updated version of my love.run:

Code: Select all

function love.run ()
	-- these don't change, so we can make them local for faster access
	local audio, graphics = love.audio, love.graphics
	local event, timer = love.event, love.timer

	-- Prepare stuff
	if love.load then love.load(arg) end

	local timestep = 1/240
	local accumulator = 0
	-- Set a reasonable FPS limit
	local min_frame_time = 1/60

	-- Main loop
	while true do
		-- Update the timer
		if timer then
			timer.step()
			accumulator = accumulator + timer.getDelta()
		end

		-- Process events
		if event then
			for e, a, b, c in event.poll() do
				if e == "q" then
					if not love.quit or not love.quit() then
						if audio then audio.stop() end
					end
					return
				end
				love.handlers[e](a, b, c)
			end
		end
		
		-- Do the game mechanic
		if love.update then
			if timer then
				while accumulator >= timestep do
					love.update(timestep)
					accumulator = accumulator - timestep
				end
			else
				love.update(0)
			end
		end

		-- Draw the graphics
		if graphics then
			graphics.clear()
			if love.draw then love.draw() end
		end

		-- Wait for the end of this frame
		if timer then
			timer.step()
			local work_time = timer.getDelta()
			if work_time < min_frame_time then
				timer.sleep((min_frame_time - work_time) * 1000)
			end
			accumulator = accumulator + work_time
		end

		-- Show the frame
		if graphics then
			graphics.present()
		end
	end
end
I haven't implemented the interpolation, because I felt this would make stuff more complicated on the user side. But to some extent you can avoid the problems by making the timestep few times smaller than graphics frame time.