Jump to content

Nearest Element


ShayF2

Recommended Posts

I was working on a script getting nearest elements, maybe someone will find this of use. This code is NOT tested, so it may need some modifications, but it's a basic platform. Note it contains a lot of looping and is set clientside so it may suck quite a bit of work out of a users computer, causing an fps drop. However I made it so that only rendered elements are checked, so that should reduce the amount of work.
Here's the code.
 

local timers = {}
local positions = {}
local objectids = {'1221'}

function checkElements(element,x1,y1,z1)
    local x2,y2,z2 = getElementPosition(v)
    local distance = getDistanceBetweenPoints3D(x1,y1,z1,x2,y2,z2)
    table.insert(postions,{element,x2,y2,z2,distance})
end

function getNearestElement(element)
    if isElement(element) then
        local elementTypes = {'vehicle','player','ped','object'}
        local x1,y1,z1 = getElementPositon(element)
        positions = {}
        for i=0,#elementTypes do
            for k,v in pairs(getElementsByType(elementTypes[i]))
                if isElementOnScreen(element) then
                    if elementTypes[i] == 'object' then
                        for l=0,#objectids do
                            if getElementModel(v) == objectids[l] then
                                checkElements(v,x1,y1,z1)
                            end
                        end
                    else
                        checkElements(v,x1,y1,z1)
                    end
                end
            end
        end
    end
    local distances = {}
    for s,t in ipairs(positions) do
        table.insert(distances,t[5])
    end
    table.sort(distances)
    for c,d in pairs(positions) do
        if d[5] == distances[1] then
            return d
        end
    end
end

addEventHandler('onClientPlayerJoin',root,function()
    source = source
    timers[source] = setTimer(function()
        getNearestElement(source)
    end,1000,0)
end)

addEventHandler('onClientPlayerQuit',root,function()
    if isTimer(timers[source]) then
        killTimer(timers[source])
    end
end)

 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...