Addition of delta time to RenderStepped

The first parameter given to the function of RenderStepped should be delta time. If you do anything using RenderStepped dealing with velocity and not using delta time, the math is wrong.

Current code:

local time=tick()
game:GetService('RunService').RenderStepped:connect(function()
local newtime=tick()
local dt=newtime-time
time=newtime
end)

New code:

game:GetService('RunService').RenderStepped:connect(function(dt)
end)
1 Like

will suggest

Yes PLEASE. I do this construct too many times:

while true do
local t = tick()
RenderStepped:wait()
local dt = tick() - dt
end

It would be great to shorten it to:

while true do
local dt = RenderStepped:wait()
end

I actually made a ModuleScript for this a while ago:

local RenderStepped = require(game.ReplicatedStorage.RenderStepped)

print("Delta of 'wait' returns:", RenderStepped:wait())

RenderStepped:connect(
	function(dt)
		print("Delta of first connection: " .. dt)
	end
)

local var = RenderStepped:connect(
	function(dt)
		print("Delta of second connection: " .. dt)
	end
)

wait(1)
var:disconnect()

Once this update is out (if it will be made to work this way, that is) you only have to edit one line to make it work with the original RenderStepped event. Namely replace:

local RenderStepped = require(game.ReplicatedStorage.RenderStepped)

With:

local RenderStepped = game["Run Service"].RenderStepped

Module code included below:

local Event = game["Run Service"].RenderStepped

local RenderStepped = {}

-- Table as return value of :connect()
local Connection = {}
Connection.__index = Connection

-- Will hold all of the connected functions:
local connections = {}

-- Loop over connected functions and remove self:
function Connection:disconnect()
	for i,v in pairs(connections) do
		if v == self.value then
			table.remove(connections, i)
		end
	end
end

-- Connect a function by putting it into 'connections':
function RenderStepped:connect(func)
	table.insert(connections,func)
	local self = setmetatable({}, Connection)
	self.value = func
	return self
end

function RenderStepped:wait()
	local t = tick()
	Event:wait()
	return (tick() - t)
end

-- To calculate dt at every event:
local current = tick()

Event:connect(
	function()
		local dt = tick() - current
		-- Loop over items (in form of function(dt)) and call:
		for _,v in pairs(connections) do
			v(dt)
		end
		current = tick()
	end
)

return RenderStepped

Throw time in too. Stepped returns both the delta and time (wait() inherently does too), and I’ve had a few times where it’s made coding something just a tad easier.