How To Correctly 'Impulse' A Spring (Hooke's Law)

Heya there!

So I’ve been very intrigued with code-based springs recently, so I sought out to making one my own just for fun. After scouring the youtube and finding a video, I formed something which you can see down below.

--[[
hooke's law: F = -k * x

k being spring constant 
x being displacement
]]

local RNS = game:GetService("RunService")

local target = 5
local initial = 8
local tension = .015
local dampening = .1
local speed = 0

RNS.Heartbeat:Connect(function()
	local displacement = (target - initial)
	local acceleration = (tension * displacement)
	local damper = (dampening * speed)
	
	speed += acceleration - damper
	initial += speed

	workspace.Test.Position = Vector3.new(-8.025, initial, 44.45)
end)

local function Set(num: number)
	initial = num
end

while true do
	Set(8)
	task.wait(3)
	
	Set(2)
	task.wait(3)
end

And now you ask, what am I asking for? Take a look at this GIF.

RobloxStudioBeta_6G7EnKa91P

The thing that’s making it go up and down is this segment of the code:

while true do
	Set(8)
	task.wait(3)
	
	Set(2)
	task.wait(3)
end

As you can see, it practically instantly ‘teleports’ from the rest state to 8 or 2. What I want to achieve is for it to not teleport, but act like an actual spring. I want it to smoothly ‘tween’ to what I want to set it to.

I’m not smart enough to fully grasp the concept of the formula, so I’m hoping I could get some help from somebody.

3 Likes

Solved by just replacing initial = num with speed = num.

Also, it looks like I can only add/subtract the spring and not set it to a specific number (it doesn’t go the way I want it to) but it’s fine.