Cause PED to flee on using item

Hello, I’ve been working with ox_inventory and I’m trying to make an item that causes a few nearby peds to flee when it is used. I think I’m on the right track, but I’m still getting no results. Any help would be appreciated!

	local pos = GetEntityCoords(GetPlayerPed(-1))
    local rped = GetRandomPedAtCoord(pos['x'], pos['y'], pos['z'], 20.05, 20.05, 20.05, 6, _r)
    local rped2 = GetClosestPed(pos['x'], pos['y'], pos['z'], 20.05, 1, 0, 0, 0, -1)
	ox_inventory:useItem(data, function(data)
		if DoesEntityExist(rped) then
            TaskSmartFleePed(rped, pos, 5000.0, 75, 0, 0)
        end
        if DoesEntityExist(rped2) then
            TaskSmartFleePed(rped2, pos, 5000.0, 75, 0, 0)
        end
	end)
end)```

Maybe you could use the TaskReactAndFleePed native?

Example:

TaskReactAndFleePed(rped, PlayerPedId())
1 Like

Fantastic, thank you!

I’ll need to work on refactoring to affect more than one ped, but this is a great start, thank you!

It looks like your code is mostly correct, but there is one issue that could be causing it not to work.

The GetRandomPedAtCoord function returns a random ped within a certain radius, so it’s possible that no peds are within the specified range of the player’s coordinates. In this case, the rped variable would be nil, and the DoesEntityExist check would fail.

To address this issue, you could try increasing the radius or using a different method to find nearby peds, such as the GetNearbyPeds function from the NativeUI library. Additionally, you may want to consider adding some debug messages or logging to help diagnose any issues.

Here’s an updated version of your code with some additional comments and debugging output:

ox_inventory:useItem(data, function(data)
    -- Get the player's current position
    local pos = GetEntityCoords(GetPlayerPed(-1))

    -- Find the closest ped to the player
    local rped = GetClosestPed(pos['x'], pos['y'], pos['z'], 20.05, 1, 0, 0, 0, -1)

    -- Debugging output to check if a ped was found
    if rped ~= nil then
        print("Found ped " .. rped .. " within range")
    else
        print("No peds within range")
    end

    -- If a ped was found, make them flee from the player
    if DoesEntityExist(rped) then
        TaskSmartFleePed(rped, pos, 5000.0, 75, 0, 0)
    end
end)

I am not familiar with the ox_inventory framework as I use my own custom inventory system. However, based on your code, I have inferred the general idea of what you were attempting to achieve. I have not yet tested this code, let me know if it works for you.

1 Like

I will give it a try when I get back to my PC. The logic looks right, but I didn’t find the GetNearbyPeds in the native page.

Whoops lol, I meant GetPedNearbyPeds not GetNearbyPeds. I’m not sure if that even exists, anyways.
Here you go: GetPedNearbyPeds - FiveM Natives @ Cfx.re Docs

1 Like