DeltaWait in RenderStepped

So… I’m not sure how to explain this exactly, but pretty much:

I need to make RenderStepped connection locked to some specific fps,
and return whenever it shouldn’t run(?) I have no idea how to describe it, my bad.

My code atm:

local main do
    local accumulated,fps: number = 0, 1/60

    function main(step)
        if fps > accumulated then
            accumulated += step
            return
        else
            accumulated = 0
        end
    
        update()
    
        animations[state]()
    end
end

Any help appreciated, thanks!

If I understood correctly, do you want the function to run continuously based on a fixed “FPS”?

The way I would approach this, based on your description, is this:

local Time_Passed = 0
local FPS = 1 / 60

local function Main_Function(...)
	-- your code
end

game:GetService("RunService").RenderStepped:Connect(function(Frame_Time)
	Time_Passed += Frame_Time -- Add the delta time to Time_Passed.
	
	if Time_Passed > FPS then -- If Time_Passed exceeds the FPS value...
		Time_Passed -= FPS * (math.floor(Time_Passed / FPS)) -- Subtract FPS from Time_Passed.
		
		Main_Function(1, 2, 3, 4, 5) -- Run function.
	end
end)

If you need to add Frame Skipping (if the user runs at 30 FPS, but your script requires 60), that is possible. My implementation is rather simple and inefficient, but for non-intensive processes, it should be enough (The same effect can be achieved more accurately by having your functions utilize the delta time too).

local Time_Passed = 0
local FPS = 1 / 60

local function Main_Function(...)
	-- your code
end

game:GetService("RunService").RenderStepped:Connect(function(Frame_Time)
	Time_Passed += Frame_Time -- Add the delta time to Time_Passed.

	if Time_Passed > FPS then -- If Time_Passed exceeds the FPS value...
		local Frame_Skips = math.floor(Time_Passed / FPS) -- If the user runs at 30 FPS, but your code needs 60, you can try using Frame Skipping. This is just a simple implementation.
		Time_Passed -= FPS * Frame_Skips -- Subtract FPS from Time_Passed.

		for _ = 1, Frame_Skips do
			Main_Function(1, 2, 3, 4, 5)
		end
	end
end)
1 Like

Well the operation I need this for is local tweening animator… There are reasons why I need this and it might be considered heavy task.
Anyways thanks for this amazing help and thanks for the frame skipping idea… I will probablly need it in future(lol).

Anyways I changed one thing, which is Time_Passed -= FPS to: Time_Passed = 0
because there is no reason to do that I think?

Anyways I tested this and it works flawlessly, thanks!

1 Like

I prefer Time_Passed -= FPS since I think it would better sync in real-time, but whatever works for you is fine. :slight_smile:

I just now noticed too I did not multiply FPS to Frame_Skips, so that could possibly fail anyways lol. I’ll just edit my answer a bit.

1 Like