I’ve been editing an open-sourced boat code to my liking for some time. The script runs a continuous loop, and changes the speed/direction of the boat via the inputs of the driver via a vehicle seat.
It would be obvious to just use :changed
but that won’t account for smooth acceleration/deceleration.
Originally it used a while wait() do
loop, but it caused significant lag, so I switched to a RunService.Heartbeat
one. Will this end all the lag in-game, or is it gonna yield the same issue, and there’s a better solution?
Here’s the code
script.Parent.MaxSpeed = script.Parent.Settings.MaxSpeed.Value
local Vehicle = script.Parent.Parent
local VehicleSeat = script.Parent
maxspeed = script.Parent.MaxSpeed
script.Parent.BodyPosition.position = script.Parent.Position
script.Parent.BodyGyro.cframe = script.Parent.CFrame
value1 = 0 --- real time speed
local bv = VehicleSeat:FindFirstChild("BodyVelocity")
local clone = bv:Clone()
local driver = false
local RunService = game:GetService("RunService")
RunService.Heartbeat:Connect(function()
if script.Parent.Throttle == 1 then
if value1 < maxspeed then value1 = value1 + script.Parent.Settings.Acceleration.Value end
script.Parent.Driving.Value = true
script.Parent.BodyVelocity.velocity = script.Parent.CFrame.lookVector*value1
script.Parent.Left.Value = false
script.Parent.Right.Value = false
end
if script.Parent.Throttle == 0 then
if value1 > 0 then
value1 = value1 -1.5
elseif value1 < 0 then
value1 = value1 +1.5
end
script.Parent.Driving.Value = false
script.Parent.BodyVelocity.velocity = script.Parent.CFrame.lookVector*value1
script.Parent.Left.Value = false
script.Parent.Right.Value = false
end
if script.Parent.Throttle == -1 then
if value1 > - maxspeed then value1 = value1 -script.Parent.Settings.Acceleration.Value end
script.Parent.Driving.Value = true
script.Parent.BodyVelocity.velocity = script.Parent.CFrame.lookVector*value1
script.Parent.Left.Value = false
script.Parent.Right.Value = false
end
if script.Parent.Steer == 1 then
script.Parent.BodyGyro.cframe = script.Parent.BodyGyro.cframe * CFrame.fromEulerAnglesXYZ(0,- script.Parent.Settings.TurnSpeed.Value,0)
script.Parent.Driving.Value = true
script.Parent.Right.Value = true
script.Parent.Left.Value = false
end
if script.Parent.Steer == -1 then
script.Parent.BodyGyro.cframe = script.Parent.BodyGyro.cframe * CFrame.fromEulerAnglesXYZ(0,script.Parent.Settings.TurnSpeed.Value,0)
script.Parent.Driving.Value = true
script.Parent.Left.Value = true
script.Parent.Right.Value = false
end
if script.Parent.Position.Y > script.Parent.BodyPosition.Position.Y then
script.Parent.Driving.Value = false
value1 = 0
script.Parent.BodyVelocity.velocity = script.Parent.CFrame.lookVector*value1
script.Parent.Left.Value = false
script.Parent.Right.Value = false
end
end)