#Spring Raycast Forces

1 messages · Page 1 of 1 (latest)

distant dagger
#

I'm making a spring with raycasts but the spring drifts

local RunService = game:GetService("RunService")

local spring = script.Parent

local springLength = 6
local restLength = 5
local stiffness = 400
local damping = 10

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Exclude
raycastParams.FilterDescendantsInstances = {spring}

RunService.Heartbeat:Connect(function(dt)
    local raycast = workspace:Raycast(spring.Position, -spring.CFrame.UpVector * springLength, raycastParams)

    if raycast then
        local hit = (spring.Position - raycast.Position).Magnitude
        local velocity = spring.AssemblyLinearVelocity
        local relVel = velocity:Dot(spring.CFrame.UpVector)

        local force = stiffness * (restLength - hit)
        local dampForce = -damping * relVel

        spring:ApplyImpulse(spring.CFrame.UpVector * (force + dampForce) * dt)
    end
end)
limpid beacon
#

could you send the code, or atleast the part you think may be the issue

distant dagger
#

oh my bad I thought I sent it

distant dagger
limpid beacon
#

so i found these issues

#

Impulse direction
You’re applying ApplyImpulse along spring.CFrame.UpVector.

If the spring isn’t perfectly aligned with the global Y axis, that vector will have X/Z components.

This means the spring receives sideways force and drifts.

Raycast and contact point
The raycast measures vertical distance but doesn’t restrict lateral motion.

The spring “floats” above the hit point, but nothing keeps it centered.

Any small deviation in orientation or velocity accumulates into sideways drift.

Realistic physics
In real life, a spring without guides would also move sideways if not constrained.
Roblox simulates this: the spring only applies force along its axis, not correcting horizontal displacement.

#

to fix it make sure spring.CFrame.UpVector always points to the global Y axis (Vector3.new(0,1,0)), if you want the force strictly vertical

#

like this: spring:ApplyImpulse(Vector3.new(0,1,0) * (force + dampForce) * dt)

distant dagger
#

thanks for the detailed reply, I'll consider this I'll be back shortly

distant dagger
distant dagger
limpid beacon
#

that is true, sorry for not considering that, since i dont use raycast too often or at all

sturdy pendantBOT
#

studio** You are now Level 1! **studio

limpid beacon
#

i just joined the server and wanted to atleast try helping someone, but seems like im no] experienced enough to do so, hope someone actually good helps you properly