How to ensure an action is performed 60 times a second?
Posted: Wed Jan 10, 2018 12:00 am
So, I'm working on a networked game and I need some data to be stored 60 times a second. Right now I'm only calling a function every love.update(), but I know that's not gonna work because framerate can vary a lot.
I've thought of doing it so a counter adds the delta time to a variable, and every time it's equal or higher than 0.01666666 it performs the function and takes 0.01666666 from the counter, leaving it usually a little higher than zero. However, I realized that maybe the delta time can be a lot higher than 0.01666666 sometimes, so I thought of checking how many times 0.01666666 can fit in whatever the number in the counter might be and performing the action the same number of times, as well as taking (0.01666666 * number of times) from the counter. Then when a second passes, the function will have been called 60 times. Is this correct?
Related to this, I was looking through the mari0 source code, and I found this odd snippet at the top of love.update(). Is this related to my problem? What does it do?
I've thought of doing it so a counter adds the delta time to a variable, and every time it's equal or higher than 0.01666666 it performs the function and takes 0.01666666 from the counter, leaving it usually a little higher than zero. However, I realized that maybe the delta time can be a lot higher than 0.01666666 sometimes, so I thought of checking how many times 0.01666666 can fit in whatever the number in the counter might be and performing the action the same number of times, as well as taking (0.01666666 * number of times) from the counter. Then when a second passes, the function will have been called 60 times. Is this correct?
Related to this, I was looking through the mari0 source code, and I found this odd snippet at the top of love.update(). Is this related to my problem? What does it do?
Code: Select all
dt = math.min(0.01666667, dt)
--speed
if speed ~= speedtarget then
if speed > speedtarget then
speed = math.max(speedtarget, speed+(speedtarget-speed)*dt*5)
elseif speed < speedtarget then
speed = math.min(speedtarget, speed+(speedtarget-speed)*dt*5)
end
if math.abs(speed-speedtarget) < 0.02 then
speed = speedtarget
end
if speed > 0 then
for i, v in pairs(soundlist) do
v:setPitch( speed )
end
music.pitch = speed
love.audio.setVolume(volume)
else
love.audio.setVolume(0)
end
end
dt = dt * speed
gdt = dt
if frameadvance == 1 then
return
elseif frameadvance == 2 then
frameadvance = 1
end
if skipupdate then
skipupdate = false
return
end