spring.lua 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. local RunService = game:GetService("RunService")
  2. local ReplicatedStorage = game:GetService("ReplicatedStorage")
  3. local character = script.Parent
  4. local springModel = ReplicatedStorage.spring
  5. springModel.Parent = workspace
  6. local current = springModel.Current
  7. local goal = springModel.Goal
  8. local velocityAngle = 0
  9. local velocityAxis = Vector3.new(1,0,0)
  10. local stiffness = 3
  11. local damping = 1
  12. function stepSpring(dt)
  13. local currentOrientation = current.CFrame - current.CFrame.p
  14. local goalOrientation = goal.CFrame - goal.CFrame.p
  15. local offset = goalOrientation:inverse() * currentOrientation
  16. local offsetAxis, offsetAngle = offset:ToAxisAngle()
  17. -- hookes law: F = -kx - bv
  18. -- if you know lots of cool calculus you can do some
  19. -- differential equations and get this as a function
  20. -- of dt but im bad at math and dont know how that works :(
  21. local force = -stiffness * offsetAngle
  22. force = force - (velocityAngle * damping * (1/dt))
  23. local dt_acceleration_mat = CFrame.fromAxisAngle(offsetAxis, force * dt)
  24. local dt_velocity_mat = CFrame.fromAxisAngle(velocityAxis, velocityAngle) * dt_acceleration_mat
  25. velocityAxis, velocityAngle = dt_velocity_mat:ToAxisAngle()
  26. current.CFrame = current.CFrame * dt_velocity_mat
  27. end