Set location to closest location

Hi all, So i have a small script where i fill some vector 3 coords in, if i want to go the the garage the script will set a location where the closest garage is. But if i drive on some parts of the map and put start this script, the location is set to almost xy 0. How can i solve this?

function garageToggle()
    local coords = GetEntityCoords(PlayerPedId())
    local closest = 1000
    local closestCoords2

    for k,v in pairs(garage) do 
        local dstcheck = GetDistanceBetweenCoords(coords, v)

        if dstcheck < closest then
            closest = dstcheck
            closestCoords2 = v
        end
    end
   
    SetNewWaypoint(closestCoords2)
    exports['okokNotify']:Alert("TomTom", "De TomTom staat ingesteld naar de dichtsbijzijnde garage!", 5000, 'success')
end

garage = {
    vector3(-1016.9838, -2864.9395, 13.9514),
    vector3(1018.42, -2511.6399, 28.4731),
    vector3(348.4991, -1692.5453, 32.5365),
    vector3(-329.19, -1516.85, 27.5343),
    vector3(-987.31, -1437.85, 5.1852),
    vector3(845.934, -909.7055, 25.2643),
    vector3(413.1789, -995.7588, 29.3919),
    vector3(-86.3944, -992.0943, 22.3918),
    vector3(-1979.0739, -311.2674, 44.106),
    vector3(-895.43, -153.7399, 36.6105),
    vector3(277.3765, -345.6028, 44.9199),
    vector3(979.5551, 8.3431, 81.0426),
    vector3(-696.0662, 294.0643, 82.967),
    vector3(-3252.02, 982.02, 12.6057),
    vector3(-1923.5537, 2047.9187, 140.7341),
    vector3(2663.5254, 1641.9822, 24.591),
    vector3(1770.14, 3337.9299, 41.4333),
    vector3(3800.5, 4448.6401, 4.2673),
    vector3(2137.0601, 4796.3701, 41.1324),
    vector3(-37.22, 6419.8101, 31.4909),

I could be wrong but it could be how you are passing the coordinates to the native functions. Just before you set the waypoint print out the coordinates to see if it is actually returning something valid.

print("X: " .. (closestCoords2.x or "nil") .. " , Y: " .. (closestCoords2.y or "nil") .. " , Z: " .. (closestCoords2.z or "nil"))

It could be that SetNewWaypoint doesnt like the vector3 that it is supplied. It may need the x , y individually, i.e.

 SetNewWaypoint(closestCoords2.x, closestCoords2.y)

Hope this helps. Happy coding !

local closest = 1000 -- If your closest garage is farther than this you do nothing at all
local closestCoords2 -- This defaults to Vector3.zero
-- Imagining that you skip the if check because you are too far from any coordinate so it does nothing anyway
SetNewWaypoint(closestCoords2) -- You are setting the waypoint to a default Vector3 value, which will be 0, 0, 0

Edit – your fix is starting at a higher distance, like 5000 because that’s roughly the size of the map.

Hi,
Thx for the answer. I’m not a good developer at all and this is a code that I have copied from another script. So your telling me that if i change local closest = 1000 to 5000 should fix it?

I will give it a try! Thx

1 Like