'How to get closest player (FiveM Lua)

This is a question regarding FiveM Scripting using the LUA language;

I want to get the ID or name of the closest player to the player executing the event. How do I get this? I currently have: (Client.lua)

    while true do
        Citizen.Wait(0)
        local ped = GetPlayerPed(-1)
        if IsPedInAnyVehicle(ped, false) then
            local vehicle = GetVehiclePedIsIn(ped, false)
            TriggerServerEvent("cartag:checkTagged")
        end
    end
end)

It then triggers the server event:

-- Checks if player is tagged
AddEventHandler("cartag:checkTagged", function()
    local ped = source
    if tableIndex(tag, ped) then
        local indexNr = tableIndex(tag, ped)
        if tag[indexNr].tagged then
            TriggerClientEvent("cartag:playerIt", ped)
        end
    end
end)

And then goes back to the client event:

-- When player is it
AddEventHandler("cartag:playerIt", function()
    local ped = GetPlayerPed(-1)
    local vehicle = GetVehiclePedIsIn(ped, false)
    local t, distance = GetClosestPlayer()
    if IsPedInAnyVehicle(t, false) then
        if HasEntityCollidedWithAnything(vehicle) then
            local dis = Vdist(coords.x, coords.y, coords.z, coordsFront.x, coordsFront.y, coordsFront.z)
            if dis <= 1.2 then
                -- Trigger tag event
                TriggerServerEvent("cartag:tag", closestPlayerId)
            end
        end
    end
end)

The GetClosestPlayer looks like this:

    local players = GetPlayers()
    local closestDistance = -1
    local closestPlayer = -1
    local ped = GetPlayerPed(-1)
    local coords = GetEntityCoords(ped)

    for i, v in ipairs(players) do
        local target = GetPlayerPed(v)
        if (target ~= ped) then
            local targetCoords = GetEntityCoords(GetPlayerPed(v))
            local distance = Vdist(targetCoords.x, targetCoords.y, targetCoords.z, coords.x, coords.y, coords.z)
            if (closestDistance == -1 or closestDistance > distance) then
                closestPlayer = v
                closestDistance = distance
            end
        end
    end
    return closestPlayer, closestDistance
end

This also calls upon:

    local players = {}
    for _, player in ipairs(GetActivePlayers()) do
        local ped_ = GetPlayerPed(player)
        table.insert(players, ped_)
    end
    return players
end

Somehow this always gives a random number when testing, with the distance pointing towards a spawn point under the map, in the northern part of the city.

So; How do I check who the closest player is, how far this player is and if that player is in a car? Thanks in advance! (Tried things from other topics, but they didn't seem to work) Note: I don't want to use ESX, want to make the script stand alone. (It's a tag game script for cars... sounds weird, don't blame me x) )



Solution 1:[1]

I don't know if this will help you but you can try one of these functions:

https://runtime.fivem.net/doc/natives/?_0x7196842CB375CDB3

https://runtime.fivem.net/doc/natives/?_0xC33AB876A77F8164

I personally use this function below to get the distance(for localchat but should work in your case too) that I made for my JS framework.

Lua converted version:

for i = 1, 255, 1 do
    if NetworkIsPlayerActive(i) then
        local player = GetPlayerFromServerId(id)
        local me = GetPlayerServerId(i)
        local coords = GetEntityCoords(GetPlayerPed(i))
        local mycoords = GetEntityCoords(GetPlayerPed(player))
        local dist = Vdist(mycoords, coords)
        
        if me == id or dist <= 15 then
            TriggerEvent('chat:addMessage', { args = { 'It works' }, color: { 230, 171, 255 } })
            break
        end
    end
end

Original JS version: https://github.com/Jones3106/NodeRP/blob/master/client/events.js#L27

RegisterNetEvent('NodeRP.Client.SendLocalMsg');
onNet("NodeRP.Client.SendLocalMsg", (name, id, msg) => {
    for (let i = 0; i < 255; i++) {
        if (NetworkIsPlayerActive(i)) {
            let player = GetPlayerFromServerId(id);
            let me = GetPlayerServerId(i);
            let coords = GetEntityCoords(GetPlayerPed(i));
            let mycoords = GetEntityCoords(GetPlayerPed(player));
            let dist = Vdist(mycoords, coords);
            
            if(me == id || dist <= 15) {
                emit('chat:addMessage', { args: [ `${name} ${NodeRP.Locales[Config.Locale]["localchat"]}: ${msg}` ], color: [230, 171, 255] });
                break;
            }
        }
    }
});

Hope it helps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SK73106