Messing around with a springs

Simply put im trying to create a spring. The spring mechanics for the position aspect works just fine, however the spring for the orientation seems to go nuts if a certain angle is reached.

Gifs of the springs

https://gyazo.com/310bd3e6535985f5413e654564e7be6a
https://gyazo.com/0ac74dee38b8cb5a69c476d4a288601d
https://gyazo.com/a1fb1000a4a75aff49514a542472573f

Code
wait(3)

local RunService = game:GetService("RunService")
local SpringPart = workspace.SpringPart
local SpringTarget = workspace.SpringTarget

local function DoSpring(Dampening, k)
	local Velocity = Vector3.new(0,0,0)
	local AngularVelocity = Vector3.new(0,0,0)
	
	RunService.RenderStepped:Connect(function(Step)
		local PosDiff = SpringTarget.Position - SpringPart.Position
		local OrientationDiff = SpringTarget.Orientation - SpringPart.Orientation

		Velocity = Velocity + Step*PosDiff*k - Dampening*Step*Velocity
		AngularVelocity = AngularVelocity + (Step*OrientationDiff*k - Dampening*Step*AngularVelocity)
		
		local NewOrientation = SpringPart.Orientation + AngularVelocity
		SpringPart.Position = SpringPart.Position + Velocity
		SpringPart.Orientation = SpringPart.Orientation + AngularVelocity
	end)	
end



local Dampening = 2
local k = 2

DoSpring(Dampening, k)


1 Like

Taking a quick look I’d guess that it is because the orientation is represented in a cyclic modulus field. The shortest distance isn’t always by subtraction, but possibly by addition. When any component of the angle would have left the least positive residue mod 360, the orientation jumps. Building velocity to reach this new orientation, it may overcorrect and cross the boundary again causing yet more, in mathematical terms, craziness.

But that is just a hunch. Let me know if dealing with that fixes it. (You need to check if adding rather than subtracting an angle is faster).

On a side note, people use quaternions to avoid issues like this with angles. Cyclic fields, gymbol locks, and random constants are bad for ones mental health. (360, really? Who comes up with this crap?)

3 Likes