[HELP] Get closest entity between multiple types of objects

Hi everyone !

I’m currently working on a phone system where you would be able to hack traffic lights.
But, since yesterday, when i started i met a problem.

My problem is:
Drawing a line between the player and the nearest traffic light no matter the type of traffic light and wich is on the screen. Because their is 3 types (Different model) so 3 different hash of Traffic lights… And, GetClosestObjectOfType() accept only 1 argument for the Hash.

So i tried to use a Table with all my hash and going trough all of them to get the nearest traffic light of any type in a certain radius, but this draw me 3 lines if their is 3 types of traffic light nearby me and if they are on my screen…

Imgur

I wan’t only one traffic light of any type, and the nearest.

A part of my script (client.lua):

local usingPhone = false

local hash = {
    trafficlight = {
        -655644382,
        862871082,
        1043035044
    }
}

Citizen.CreateThread(function()
    while true do
        Wait(1)
        if IsControlJustPressed(1, 27) then
            if usingPhone then
                usingPhone = false
                PhoneOutAnim()
            else
                usingPhone = true
                SetCurrentPedWeapon(GetPlayerPed(-1), 0xA2719263)
                PhoneInAnim()
            end
        end

        if usingPhone then
            local x1,y1,z1 = table.unpack(GetEntityCoords(GetPlayerPed(-1)))

            for k,v in ipairs(hash.trafficlight) do
                local closestObject = GetClosestObjectOfType(x1, y1, z1, 30.0, v, false, false, false)
                local x2,y2,z2 = table.unpack(GetEntityCoords(closestObject))
                local onScreen,x,y=World3dToScreen2d(x2,y2,z2)
                
                if DoesObjectOfTypeExistAtCoords(x1, y1, z1, 30.0, v) and onScreen then
                    DrawLine(x2, y2, z2, x1, y1, z1, 255, 255, 255, 255)
                end
            end
        end
    end
end)

I really dont know how to do it and where to start. Any help will be appreciated !

Thank you :slight_smile:

1 Like