Spring Physics Simulation on a 2D Surface

Last post for today!

I saw this cool video later today, and found this nice explanation of spring forces on a 2D plane. So I tried learning something new and add onto what I already had learnt, just with a few tweaks and created this!


Try for yourself!

https://www.roblox.com/games/7305657428/Spring-Simulation

Source -

local spring = {}

function spring.new(bob)
	local center = workspace.CurrentCamera.ViewportSize/2
	
	local disp = 200
	local y = 250
	local k = .01
	local v = Vector2.new(0, 0)
	local anch = Vector2.new(center.x, 0)
	local pos = center + bob.AbsoluteSize/2
	local gravity = Vector2.new(0, .1)
	local damp = 0.998
		
	game:GetService("RunService").Heartbeat:Connect(function()
		if game:GetService("UserInputService"):IsMouseButtonPressed(Enum.UserInputType.MouseButton1) then
			local mousepos = game:GetService("UserInputService"):GetMouseLocation()
			bob.Position = UDim2.new(0, mousepos.x, 0, mousepos.y)
			pos = mousepos
			v = Vector2.new(0, 0)
		else
			bob.Position = UDim2.new(0, pos.x, 0, pos.y)

			local force = pos - anch
			local mag = force.magnitude - disp
			force = force.Unit
			force = force * -1 * k * mag
			v += force + gravity
			pos += v
			v = v * damp	
		end
	end)
end

return spring

Thanks!

2 Likes

Added a rope to the bob, It feels more alive now :slight_smile:

Wow, nice work! I have recently created a suspension using spring constraints, but it won’t work on 2d surfaces of course. I tried messing with equations but all flew above my head :airplane:

Great job with this!

1 Like

yes also

also @jaipack17 nice concept

2 Likes