My goal is to make a spaceship that hovers in the air.
Everything works good enough, but the problem is that the way I scripted this causes the data that I provided to be somewhat incorrect.
The main problems includes how the drag for the spaceship/aircraft doesn’t matchup with the acceleration. The drag also causes the spaceship to stop before the currentSpeed reaches 0, so the data is completely broken since the spaceship could be in place, but the speed says it’s still going 10 miles per hour.
For a better picture, I have a video that showcases my creation.
MaxSpeed = 50, -- 50 studs per second
Steering = 20, -- 20 degrees per second
Acceleration = 1 -- 1 stud per second
RunService.RenderStepped:Connect(function(dt)
local drag = (1 - (aircraftValues.currentSpeed / aircraftValues.maxSpeed))
local CoordinateFrame = camera.CFrame
local Movement = Vector3.new(0, 0, 0)
-- Example throttle calculation: 1 if moving, 0 if not. Replace with real throttle input if available.
local throttle = 0
if hum.MoveDirection.Magnitude > 0 then
throttle = 1
else
throttle = 0
end
-- Accelerate or decelerate based on throttle
aircraftValues.currentSpeed = aircraftValues.currentSpeed + (aircraftValues.acceleration * throttle * dt)
-- Apply drag (natural deceleration)
if throttle == 0 then
aircraftValues.currentSpeed = aircraftValues.currentSpeed - (aircraftValues.acceleration * 0.5 * dt)
end
aircraftValues.currentSpeed = math.clamp(aircraftValues.currentSpeed, 0, aircraftValues.maxSpeed)
if throttle > 0 then
local localControlVector = CFrame.new(Vector3.new(0,0,0),CoordinateFrame.lookVector*Vector3.new(1,0,1)):vectorToObjectSpace(hum.MoveDirection+Vector3.new(0,.2,0))
Movement = CoordinateFrame:vectorToWorldSpace(localControlVector.Unit)
end
aircraftValues.momentum = (aircraftValues.momentum * drag) + (Movement * aircraftValues.currentSpeed)
linearVelocity.VectorVelocity = aircraftValues.momentum
if hum.MoveDirection.Magnitude > 0 then
bodyGyro.CFrame = (CFrame.new(Vector3.new(0,0,0), aircraftValues.momentum))
else
bodyGyro.CFrame = (CFrame.new(Vector3.new(0,0,0), vehicle:GetPivot().LookVector))
end
end)