im attempting to create a raycast suspension but the problem is that it keeps going up
i think how im caculating the forces but im lost really, ive even tried clamping the force but that didnt work
Suspension Class
local Suspension = {}
Suspension.__index = Suspension
function Suspension.new(part, height, length, stiffness, damping)
local self = setmetatable({}, Suspension)
self.part = part
self.height = height
self.length = length
self.stiffness = stiffness
self.damping = damping
local size = part.Size / 2
local frontLeftCorner = part.CFrame * CFrame.new(size.X, -self.height, -size.Z)
local frontRightCorner = part.CFrame * CFrame.new(-size.X, -self.height, -size.Z)
local rearLeftCorner = part.CFrame * CFrame.new(size.X, -self.height, size.Z)
local rearRightCorner = part.CFrame * CFrame.new(-size.X, -self.height, size.Z)
self.corners = {frontLeftCorner, frontRightCorner, rearLeftCorner, rearRightCorner}
self.restingPosition = part.CFrame
return self
end
function Suspension:update(dt)
local forces = Vector3.new()
for i = 1, #self.corners do
local corner = self.corners[i]
local ray = Ray.new(corner.Position, corner.UpVector * -self.length)
local hit, position, normal = workspace:FindPartOnRayWithIgnoreList(ray, {self.part})
if hit then
local distance = (corner.Position - position).Magnitude
local compression = self.length - distance
forces = forces + normal * compression * self.stiffness
end
end
local velocity = (self.part.CFrame.Position - self.restingPosition.Position) / dt
local dampingForce = -velocity * self.damping
dampingForce = Vector3.new(dampingForce.X, 0, dampingForce.Z)
forces = forces + dampingForce
local acceleration = forces / self.part:GetMass()
local newPosition = self.part.CFrame.Position + velocity * dt + acceleration * dt * dt
self.part.CFrame = CFrame.new(newPosition, newPosition + self.part.CFrame.lookVector) + self.part.CFrame:vectorToObjectSpace(Vector3.new(0, self.length, 0))
end
return Suspension
Usage In Script
local Suspension = require(game.ReplicatedStorage.Common.CarController)
local car = workspace.car
local part = car.PrimaryPart
local suspension = Suspension.new(part, 2, 1, 0.1, 1)
game:GetService("RunService").Heartbeat:Connect(function(dt)
suspension:update(dt)
end)