How to Retrieve Vehicle Hash with Player in It

Hello, I’m fairly new to fiveM scripting and am working on one of my first scripts so spare me if I make some mistakes.

What I want to do with the first part of this script is get the hash of the vehicle a player is shooting at.

Code I have

Citizen.CreateThread(function()
	
	local player = PlayerId()
	local ped = GetPlayerPed(-1)

  while ESX == nil do
	
		Citizen.Wait(0)
	
		if IsPlayerFreeAiming(player) then 
			
			if IsPedShooting(ped) then
			
				local aiming, entity = GetEntityPlayerIsFreeAimingAt(player, Citizen.ReturnResultAnyway())
			

					if IsEntityAVehicle(entity) then
				
						print('Shooting at car')						
				
					else 
				
						print('Not shooting at car')
					
			
				end
			end
		end	
	end
end)

Problem: When there isn’t a player in the vehicle it works fine but when there is it prints “Not shooting at car” to the console

Expected Result: I want the program to acknowledge that I am shooting at a car even if there is a player in it.

Interesting, seems like it prioritizes the ped(s) in the vehicle, my speculation is if you were pointing a weapon at a vehicle most likely you wanted to kill the ped(s) inside (e.g. shoot thru windows).

Quick fix/workaround I just came up, not tested yet

if DoesEntityExist(entity) then --extra condition, just in case
   if IsEntityAVehicle(entity) then
      -- Is Vehicle
   elseif IsEntityAPed(entity) then
         local vehicle = GetVehiclePedIsIn(entity, false)
         if vehicle then
            -- Is Vehicle
         else
            -- Is Not Vehicle
         end
   else
      -- Is Not Vehicle
   end
end

Tell me if it works :disappointed_relieved: Thank you sir, have a nice day

Thank you so much this worked for my particular situation.

1 Like

Glad it worked! Thank you for your update sir, have a great time scripting :fire: