Consistent Framerate/Hz with RunService.Renderstepped

when im testing in studio at a consistent 60 fps it gets the results i want but when i test in the roblox client because i get more frames the stamina goes down quicker. is there any way i can fix it so it always runs at a consistent 60 fps/hz no matter what the clients framerate is

this is a part of the whole script

runservice.RenderStepped:Connect(function(delta)
	local stamina = plrstats:FindFirstChild('Stamina')
	
	if stamina.Value < staminausage.Value then
		isSprinting = false
		hum.WalkSpeed = plrstats:FindFirstChild("BaseWalkSpeed").Value
		sprintanim:Stop()
		tweenservice:Create(camera, tweeninfo, {FieldOfView = 70}):Play()
		rechargeTime.Value = 3
	end
	
	if stamina.Value > 100 then
		stamina.Value = 100
	elseif stamina.Value < 0 then
		stamina.Value = 0
	end
	
	if isCrouching then
		if hum.MoveDirection.Magnitude > 0 then
			if not crouchmoveanim.IsPlaying then
				crouchmoveanim:Play()
				crouchanim:Stop()
			end
			
		else
			if not crouchanim.IsPlaying then
				crouchanim:Play()
				crouchmoveanim:Stop()
			end
			
		end
	end
	
	if isSprinting and stamina.Value > 0 and hum.MoveDirection.Magnitude > 0 and hum.WalkSpeed > 0 then
		stamina.Value -= staminausage.Value
		lastsprint = tick()
	else
		if tick() - lastsprint >= rechargeTime.Value and stamina.Value < plrstats:FindFirstChild('MaxStamina').Value then
			stamina.Value += staminaregen.Value
			rechargeTime.Value = 1
		end
	end
	staminaGUI.StaminaBar.Bar.Size = UDim2.new(1 - (1 - (stamina.Value/plrstats:FindFirstChild('MaxStamina').Value)), 0, 1, 0)
end)

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

1 Like

I assume your ‘staminausage’ and ‘staminaregen’ number values are in ‘per second’? I.e. the drain/regen per second.

If that is the case then you simply have to multiply them by dt. Since that loop isn’t running 1 time a second, but (usually) 60 times a second you have to account for the difference in speed. DeltaTime is a small value (time passed in seconds since last frame), something like 0.016 (16ms).

Multiplying a drain of ‘10/s’ will make it ‘10*0.016=0.16/frame’. So you’re doing increments of 0.16, 60 times a second. Instead of increments of 10, 60 times a second.

The multiplication by dt also handles variable framerate correctly.

3 Likes

ohhh i see. i tried something like this but i can tell now that i was doing it wrong. thanks for this

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.