I’ve been writing a simple 3d spring for the last week or so now, and i’ve managed to get it to work when the target is being updated (however, for simple springs, its not supposed to work when the target is updated, or if it does, it won’t work how it should, that’s why it needs to be driven) however while the target is moving then stops the velocity of the spring suddenly increases, and if the target goes fast the slow, the spring doesn’t keep any of its momentum?
Also, I’m pretty sure i am using a few too many variables for my spring and i’m wondering if theres a way to improve the performance of it in the process?
This is my code, so far:
wait(0.5)
local target = workspace.Target
local current = workspace.Current
local function create(c, A, B)
local s = {}
--A for decay rate, B for frequency
s.A = A
s.B = B
--s is the starting value, t is the target value, and c is the current value
s.s = c
s.t = c
s.c = c
--x is time elapsed since target not changed, v is velocity, p is previous position
s.x = 0
s.v = Vector3.new()
s.p = Vector3.new()
s.update = function(x)
--set the total time elapsed
s.x = s.x + x
--set the velocity based on change of target position
s.v = (s.t - s.p)
s.p = s.t
--the function which updates the spring
s.c = (s.s - s.t) * math.cos(s.B * s.x) * 2^(-s.A * s.x) + s.t
--when the target is moving
if s.v ~= Vector3.new() then
s.x = 0
s.s = s.c
end
end
return s
end
--creating the spring
local spring = create(Vector3.new(0, 0, 1.05), 2, 3)
current.Position = spring.c
--updating the spring
game:GetService("RunService").RenderStepped:Connect(function(s)
spring.t = target.Position
spring.update(s)
current.Position = spring.c
end)
I’m pretty sure my method of updating the spring is also having a massive performance hit on the gpu, so making sure this is efficient as possible is my aim.
And before you think im talking about physical actual springs/constraints i’m not, i’m talking about similar spring mechanics found in fps games, such as phantom forces.
Here is a video to explain what I mean.