# Help Creating My own Spring Force Physics

Hi, I’m working on a 2D top-down game and am trying to make something so that when the player collides with this spring objects “loose end” and based on a rigid body force it will be pushed back. I need to use F = - k x as a basis for my code. What I have set up so far is the spring object with a loose/fixed end.

I want to make a script using that formula of (F = - k x) that compresses the “loose end” towards the “fixed end” and based on a rigid body force pushes the player back. Trying to set-up spring force equation - distance traveled from the relaxed position, then use spring force to determine how much is force needed to compress spring and then when it will stop compressing and push the player back

What’s the problem, exactly?

The basic setup would be using the distance between both ends (x) and applying a force to anything touching the “loose end” proportionally to that distance (F = -k x).

Another option would be using a Raycast for detecting any object in the range of the spring, then applying a force to it according to the distance from the Raycast’s origin.

Both options would be a “basic straightforward” setup. The final effect will strongly depend on the actual physics time step. For instance, in t=0 there may be no object within range, but in t=0.02 (next timestep) an object may be in the middle of the spring range. A more correct implementation would integrate the spring force from the previous state (maximum elongation in this case) to the new state (half compressed) and apply the resulting force to the object.