Hello, for the past few days I have been working on creating a programmed car suspension system. For the time being, I am trying just to mimic one spring which will later be used in the place of a wheel on a car.
-
What do I want to achieve? I have a spring that works for a bit but then after moving it, it breaks.
-
What is the issue?
When just using the “Run” feature in studio it works perfectly fine, however, when actually playing it in studio or in-game, it breaks after I move it around. It looks like the damping of the spring stops working for some reason.
Also, if I set the network ownership to a player it instantly breaks and flies into the sky.
-
What solutions have I tried so far?
I’ve read through almost everything I could find about the problem. From what I could find my damping system might be wrong or I might have to add ‘limits’ to the force being applied to the part, but I am not sure where or how to implement that into my code.
My code is the following:
local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {script.Parent}
rayParams.FilterType = Enum.RaycastFilterType.Blacklist
local spring = script.Parent
local suspension_length = 4 -- max length of suspension (raycast length)
local Top = script.Parent.Top -- the spring part
local force = Top.BodyForce
local gyro = Top.BodyGyro
local stiffness = 1
local lastx = 0
local NumWheels = 1
Top:SetNetworkOwner(nil)
game:GetService("RunService").Heartbeat:Connect(function(dt)
local raycastResult = workspace:Raycast(Top.Position,Top.CFrame.UpVector * -suspension_length,rayParams)
local distance
if raycastResult then
distance = (Top.Position-raycastResult.Position).Magnitude
end
local mass = Top:GetMass()
local weight = (mass*workspace.Gravity)
local x = suspension_length - (distance or suspension_length)
local k = weight/ NumWheels + (stiffness or 0)
local d = 0.9 * 2 * (k *(mass / 4)) ^ 0.5
local spring_force = k * x
local dx = (x - (lastx or x)) / dt
local damping_force = (dx*d)
-- Force = kx + dv
force.Force = Vector3.new(0,spring_force + damping_force,0)
lastx = x
gyro.CFrame = CFrame.new(0,0,0)
end)