[HELP] set/lock vehicle speed

I am trying to setup a cruise control function that will lock the vehicles speed. I have been looking around at the FiveM native reference but can’t seem to find a native that will do that.

if IsControlPressed(0, Keys['LEFTCTRL']) and IsControlJustPressed(0, Keys['C']) then
	local ped = PlayerPedId()
	local vehicle = GetVehiclePedIsIn(ped, false)
	local speed = GetEntitySpeed(vehicle);  
	local kmh = (speed * 3.6);  
	local mph = (speed * 2.236936);  
	
	if vehicle ~= 0 then
		SetVehicleForwardSpeed(vehicle, mph)
		ShowNotification("You've locked your speed to ~g~" .. mph .. "mph~w~.")
	end
end

I have figured out how to set the vehicle speed with a while loop like this:

local cruiseControl = true
while (cruiseControl == true) do
  Citizen.Wait(0)
  SetVehicleForwardSpeed(vehicle, speed)
end

but am now trying to figure out a way to detect when the VehicleBodyHealth or VehicleEngineHealth changes to turn off the SetVehicleForwardSpeed loop.

SOLVED:

Citizen.CreateThread(function()
	while cruiseControl == true do
		Citizen.Wait(0)
		if vehicle ~= 0 then 
			if (cruiseControl == true) then 
				SetVehicleForwardSpeed(vehicle, speed)
			end
			
			if (vehicleHealth == nil) then 
				vehicleHealth = GetVehicleBodyHealth(vehicle)
			else
				local vehicleHealthThisFrame = GetVehicleBodyHealth(vehicle)
				
				if (vehicleHealth ~= vehicleHealthThisFrame) then
					cruiseControl = false 
					ShowNotification("Cruise control ~r~stopped ~w~due to ~y~vehicle damage~w~.")
					vehicleHealth = vehicleHealthThisFrame
				end
			end
		end
	end
end)

Nice work dude… Released?

1 Like

If interested I just finished a vehicle controller that includes turn signals, doors, cruise control, hood, trunk and more.

That’s nice