Native related too cars

Hi!
I was wondering if there is any native or some function to detect when a player leaves a vehicle. The native IS_PED_IN_ANY_VEHICLE only detects, at least from my understanding, when a player is entering and not leaving.
Any help would be appreciated. Thanks in advance!

1 Like

In terms of Native functions, you can use IsPedInAnyVehicle (IsPedInAnyVehicle - Natives @ Cfx.re Docs) to set that a player is inside a vehicle and then loop to detect when they have left. So it will be true when inside and if it becomes false, they have left the vehicle. I feel this is by far the most popular. It’s what I use and it’s what I keep seeing in releases.

client.lua

local wasInVehicle = false
Citizen.CreateThread(function()
	while true do
		Citizen.Wait(5)
		local inVehicle = IsPedInAnyVehicle(PlayerPedId(), false)
		if inVehicle and not wasInVehicle then
			wasInVehicle = true -- Entered vehicle
		elseif wasInVehicle and not inVehicle then
			wasInVehicle = false -- Left vehicle
		end
	end
end)

If you use baseevents, which is a stock resource (a script that comes with a FiveM server install, by default), it includes an event that does exactly this. Simply add an event handler for it in a server-sided file, then trigger a client event you create in your script, if you want.

server.lua

AddEventHandler("baseevents:leftVehicle", function(lastVehicle, lastSeat, vehicleDisplayName)
	TriggerClientEvent("myScript:leftVehicle", source, lastVehicle, lastSeat)
end)

Please keep in mind that I have never used these predefined base events, as I write my own. But they are there for you to make things like this, easier.

Appreciate the help, that first part was what I was looking for and my head was not reaching that. Much obliged

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.