Anyone got any ideas on how I can fix my code so that my spring suspension doesn’t go haywire every time the car spins?
spring = class()
function spring:init(body, right, forward, min, max, rest, stiff, damper)
self.body = body
self.right = right
self.forward = forward
self.restLength = rest or 1.5
self.springTravel = 1
self.springStiffness = stiff or 30
self.damperStiffness = damper or 10
self.minLength = self.restLength - self.springTravel
self.maxLength = self.restLength + self.springTravel
self.springLength = self.maxLength
self.wheelRadius = 0.5
end
function spring:draw()
self.rayPos = (self.body.position + (self.body.forward * self.forward) + (self.body.right * -self.right))
self.raycast = scene.physics:raycast(self.rayPos, -self.body.up, self.maxLength + self.wheelRadius)
self.lastLength = self.springLength
if self.raycast then
self.springLength = ((self.maxLength + self.wheelRadius) * self.raycast.fraction) - self.wheelRadius
else
self.springLength = self.lastLength
end
--self.springLength = math.max(self.minLength, math.min(self.maxLength, self.springLength))
self.springVelocity = (self.lastLength - self.springLength) / DeltaTime
self.springOffset = self.restLength - self.springLength
self.springForce = self.springStiffness * self.springOffset
self.damperForce = self.damperStiffness * self.springVelocity
self.suspensionForce = self.springForce + self.damperForce
if self.raycast then
self.body:get(craft.rigidbody):applyForce(vec3(0,self.suspensionForce,0), vec3(-self.right, 0, self.forward))
end
return self.rayPos, self.springLength, self.springOffset, self.suspensionForce, self.springVelocity
end