How can I make this spring module independent from the player's framerate?

title explains it

the code im using:

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()

local Spring = require(script:WaitForChild("Spring"))

local RecoilSpring = Spring.new(5, 50, 4, 10)

Mouse.Button1Down:Connect(function()
	RecoilSpring:Shove(Vector3.new(0.3, 0, 0) * (workspace:GetRealPhysicsFPS() * RunService.RenderStepped:Wait()))
end)

RunService.RenderStepped:Connect(function(DeltaTime)
	local Recoil = RecoilSpring:Update(DeltaTime)
	
	workspace.CurrentCamera.CFrame *= CFrame.Angles(Recoil.X, Recoil.Y, Recoil.Z)
end)

and this is the spring module:

local Iterations = 8

local Spring = {}
Spring.__index = Spring

function Spring.new(Mass, Force, Damping, Speed)
	local self = setmetatable({}, Spring)
	
	self.Target = Vector3.zero
	self.Position = Vector3.zero
	self.Velocity = Vector3.zero
	
	self.Mass = Mass or 5
	self.Force =  Force or 50
	self.Damping = Damping or 4
	self.Speed = Speed or 4
	
	return self
end

function Spring:Shove(Force)
	local X, Y, Z = Force.X, Force.Y, Force.Z
	
	if X ~= X or X == math.huge or X == -math.huge then
		X = 0
	end
	
	if Y ~= Y or Y == math.huge or Y == -math.huge then
		Y = 0
	end
	
	if Z ~= Z or Z == math.huge or Z == -math.huge then
		Z = 0
	end
	
	self.Velocity += Vector3.new(X, Y, Z)
end

function Spring:Update(DeltaTime)
	local ScaledDeltaTime = math.min(DeltaTime, 1) * self.Speed / Iterations
	
	for i = 1, Iterations, 1 do
		local IterationForce = self.Target - self.Position
		local Acceleration = (IterationForce * self.Force) / self.Mass
		
		Acceleration -= self.Velocity * self.Damping
		
		self.Velocity += Acceleration * ScaledDeltaTime
		self.Position += self.Velocity * ScaledDeltaTime
	end
	
	return self.Position
end

return Spring
2 Likes

solved charssssssssssssssssssssss

1 Like

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