How to make a connection be active for **exactly** 15 frames?

Hi guys!! Basically recently i’ve been trying to remake Celeste and it has a mechanic where if you dash your velocity is set to a certain number for EXACTLY 15 frames.

I’ve made a bit of code that i think should adjust to all framerates. When i run the game at 60 frames it works perfectly, yet if i set my frames per second to 240 it kind of glitches out and runs instantly, not for 15 frames (or .25 seconds if thats easier to understand). Is there a way to fix this? There definitely should be.

local framespassed = 0

local connection
connection = runservice.PreSimulation:ConnectParallel(function(deltatime)
	local framesPassedThisIteration = 1/(deltatime * 60)
	framespassed += framesPassedThisIteration
	if framespassed <= 15 then
		if not char.Parent or not char:FindFirstChildOfClass("Humanoid") or char:FindFirstChildOfClass("Humanoid").Health <= 0 then -- making sure were not dead be4 dashing
			return
		end
		task.synchronize()
		--do stuff
		task.desynchronize()
	elseif framespassed > 15 and framespassed < 21 then
		-- if 15 frames passed do stuff until we've passed 21 frames
	else
		--do stuff if we've surpassed 21 frames and are ready to stop running the presimulation connection
		task.synchronize()
		connection:Disconnect()
		task.desynchronize()
	end
end)

I’ve also looked at some posts but they don’t really clarify HOW to do this, they just say that you should make code that works for all framerates and i do not know how to do that…

please please help me, cause this is the base of my game

As far as I know, RunService.PreSimulation fires at a fixed 60 Hz physics tick, so you can just count how many ticks have happened no matter what the clients render fps is set to and that should work out

local framespassed = 0

local connection
connection = runservice.PreSimulation:ConnectParallel(function(deltatime)
    -- simply count each physics tick instead of inverting deltatime
    framespassed += 1

    if framespassed <= 15 then
        -- first 15 frames: your dash logic
        if not char.Parent or not char:FindFirstChildOfClass("Humanoid") then
            return
        end

        task.synchronize()
        -- do stuff
        task.desynchronize()

    elseif framespassed > 15 and framespassed < 21 then

    else
        task.synchronize()
        connection:Disconnect()
        task.desynchronize()
    end
end)

lmk if that doesn’t help

1 Like

very weird, when i do framespassed += 1 it still goes as fast as in the first variant, so its still not fixed.
ill try using os.clock as i think another user suggested to me (i cant quite find their reply though)

os.clock() works perfectly! i just do

local starttime = os.clock()

connection = runservice.PreSimulation:ConnectParallel(function(deltatime)
    local framespassed = 60 * (os.clock() - starttime)
end)
1 Like