Weird scripted spring behavior

Hello, I’ve been trying to script a spring which can be used for vehicles, however, it seems that the seems that the spring grows in amplitude over time causing it to be jittering and fly high into the air.

Script:

local mass = script.Parent.AssemblyMass
local weight = mass * workspace.Gravity

local k = weight + 1
local c = 2 * (k * mass) ^ 0.5

local height = 5

local p = script.Parent
local f = p.VectorForce
local last_compression = nil

game:GetService("RunService").Stepped:Connect(function(dt)
	local cf = p.CFrame
	local origin = cf.Position
	local goal = origin - cf.UpVector * height
	local dir = goal - origin
	
	local result = workspace:Raycast(origin, dir)
	
	if not result then
		last_compression = nil
		f.Force = Vector3.new()
		return
	end
	
	local length = (result.Position - origin).Magnitude
	local compression = height - length
	
	local sp = compression * k
	local velocity = (compression - (last_compression or compression)) / dt
	local dp = velocity * c
	
	last_compression = last_compression
	
	f.Force = cf.UpVector * (sp - dp)
end)

My testing place:
uh yeah.rbxl (23.4 KB)

1 Like

there is an answer given by @BanTech

i think this can help u