hey guys, as the title already explained, how does this snippet of code work?
local FPS = 20
local frametime = 0
runService.PreSimulation:Connect(function(deltaTime)
frametime += deltaTime
-- FPS CAP --
if frametime >= 1/FPS then
frametime %= 1/FPS
else
return
end
print("do something")
end
local cap = 20
local clock = os.clock()
runService.PreRender:Connect(function(deltaTime: number)
while os.clock() - clock < 1/cap do end
clock = os.clock()
end)
That doesn’t exactly limit/reduce the FPS, it just waits until enough time has passed to run the code (which is what you should do instead of intentionally limiting FPS).
It will early return if frametime (the sum of time passed) is below 1/20th of a second. If it’s equal to or over that amount, it resets frametime to the remainder of time over the limit (i.e., in normal cases, it would be equivalent to frametime -= 1/FPS) to account for error, and then runs any following code.
You keep adding how much time passes until enough time has passed. If enough time hasn’t passed, you don’t do anything. If enough time has passed, you reset the timer and run code.
Yes, the point of this is to run code at a certain rate. This is basically a timer, so it’s useful for anywhere an infinitely looping timer is needed. Typically you could see this for complex operations that need to be done regularly but are too computationally expensive to run every frame.
No. It’s something you’ll have to be judicious about whether or not it’s desired. If you have, for example, some code that updates the position of a laser based on the player’s mouse, it might look really bad if it isn’t synced with framerate. Other stuff, like NPCs or gameplay systems, are more applicable.
For the most part I think so, as it’s less confusing, but at low framerates it’s possible that timePassed compounds more and more above interval, which may or may not cause bugs.