How can I know if my code will work with all framerates?

I’m currently experimenting with springs and I’ve written this code:

local spring = {}

spring.__index = spring

function spring.new(Object, TargetPos, Tension, Dampening)
	local self = setmetatable({}, spring)
	
	self.Object = Object
	self.TargetPos = Object.Position.Y + TargetPos
	self.Tension = Tension
	self.Dampening = Dampening
	self.Speed = 0
	
	return self
end

function spring:update(dt)
	local displacement = self.TargetPos - self.Object.Position.Y
	self.Speed += (self.Tension * displacement) - (self.Dampening * self.Speed)
	self.Object.Position += Vector3.new(0,self.Speed,0);
end

return spring

The spring:update() method should run every .RenderStepped on the client. Everything works well on 60 fps but I’m not sure how this will run on slower or faster frame rates. I don’t have any way of testing this since roblox doesn’t have a built in frame rate limiter into studio. I’m still trying to understand deltatime and how I can make my code work on all frame rates, if somebody could explain to me exactly how deltatime works that would be appreciated.

You have to multiply the value changes by delta time. Delta is the time in between each frame.

I understand that, but why do I have to do that? How does it work?

To understand how to use dt you must do a unit analysis of the problem.

i.e.

  • Speed = distance / time or studs / s
  • dt = time / frame or s / frame

Notice how dt is actually just FPS but flipped, so dt = 1 / FPS. This means that at 60 FPS each frame is updating at 1/60th of a second, or dt = 1 / 60.

Let’s see how the math gets involved here:
image

Now we know how far the spring should travel every frame depending on the FPS of the system:

self.Object.Position += Vector3.new(0,self.Speed*dt,0);

You’ll notice that your springs will slow down substantially, but that’s because they’re supposed to. To fix this problem you’ll simply need to increase the tension of your springs then adjust the dampening accordingly.

1 Like