How to fix lag with cars

Every time you tab out or something, the game carries on. I know its because of Delta Time: the timer increases when the car stops moving due to lag. I’m not so sure how I would fix this though. Video for demonstration:

The reason for it breaking is due to the car stopping cause of the lag, and the carriages still moving because they are controlled by deltatime. Here is the code to calculate the speed change.

RunService.Heartbeat:Connect(function(Time)
	Speed = Seat.Velocity.Magnitude
	local Point = CFrame.new(Driver.PrimaryPart.Position) * CFrame.Angles(0, math.rad(Driver.PrimaryPart.Orientation.Y), math.rad(Driver.PrimaryPart.Orientation.Z))
	
	if Spline == nil then
		Spline = BusMovement.AddPointToSpline(Point)
	else
		BusMovement.AddPointToSpline(Point, Spline)
	end
	
	Distance += Time * Speed

	for Count = 1, #Cars do
		if Distance - Cars[Count].Lag >= 0 then
			Point = BusMovement.DistanceAlongSpline(Spline, Distance - Cars[Count].Lag)
			Cars[Count].Part.CFrame = CFrame.lookAt(Point[1].Position, Point[2].Position)
		else
			Cars[Count].Part.CFrame = CFrame.new(0, 50, 0)
		end
	end
	
end)

The code for the cars movements

local function Update(DeltaTime)
	
	local SteerGoal = -Seat.SteerFloat * MaxSteerAngle
	Steer = Steer + (SteerGoal - Steer) * math.min(DeltaTime * Seat.TurnSpeed, 1)
	
	AttachmentFL.Orientation = Vector3.new(0, Steer, -90)
	AttachmentFR.Orientation = Vector3.new(0, Steer, -90)
	
	if Driver.Name == "Truck" then
		WheelBL.Orientation = PhysicalWheelFL.Orientation
		WheelBR.Orientation = PhysicalWheelFR.Orientation
	end
	
	local Torque = Seat.Torque
	CylindricalBL.MotorMaxTorque = Torque
	CylindricalBR.MotorMaxTorque = Torque
	CylindricalFL.MotorMaxTorque = Torque
	CylindricalFR.MotorMaxTorque = Torque
	
	local Speed = Seat.MaxSpeed
	local ThrottleGoal = Seat.ThrottleFloat + 0.5
	
	Throttle = Throttle + (math.min(ThrottleGoal, 1) - Throttle) * math.min(DeltaTime * (Seat.TurnSpeed * 1.5))
	
	local CurrentSpeed = Speed + (10 * Throttle)
	
	CameraEvents.ChangeFOV(70 + (10 * Throttle))
	CylindricalBL.AngularVelocity = CurrentSpeed
	CylindricalBR.AngularVelocity = -CurrentSpeed
	CylindricalFL.AngularVelocity = CurrentSpeed
	CylindricalFR.AngularVelocity = -CurrentSpeed
end

RunService.Heartbeat:Connect(Update)
1 Like