How can i teleport a player to the nearest coord?

Hey, i want to teleport a player to the nearest coord, like:

local randomCoords = {
{ x,y,z, },
{ x,y,z, },
{ x,y,z, },
{ x,y,z, },
}

and teleport the player to the near randomCoords location

Are these ‘nearest coords’ coords you’re configuring yourself or does it need to teleport the player to a random location within a specific radius?

I’m setting up myself

Don’t know for sure but think this might work:

local coords = {
    vector4(0, 0, 0, 0), -- EQUALS TO x, y, z, h
    vector4(0, 0, 0, 0),
    vector4(0, 0, 0, 0),
    vector4(0, 0, 0, 0)
}

RegisterNetEvent('esx:teleportPlayerToRandomCoords')
AddEventHandler('esx:teleportPlayerToRandomCoords', function()
    -- GET RANDOM LOC
    local random = math.random(1,#coords)
    TeleportLocation = {
        x = coords[random][1],
        y = coords[random][2],
        z = coords[random][3],
        h = coords[random][4]
    }

    teleportPlayer(TeleportLocation)
end)

teleportPlayer = function(pos)
    local entity = GetPlayerPed(-1)
    
    DoScreenFadeOut(200)
    Citizen.Wait(200)
    SetEntityCoords(entity, pos.x, pos.y, pos.z, 0, 0, 0, false)
    SetEntityHeading(entity, pos.h)
    PlaceObjectOnGroundProperly(entity)
    Citizen.Wait(1500)
    DoScreenFadeIn(200)
end

Try this

local randomCoords = {
    vec(x, y, z),
    vec(x, y, z),
    vec(x, y, z)
}

-- sort by distance
local currentCoords = GetEntityCoords(PlayerPedId())
table.sort(randomCoords, function(a, b)
    return #(a - currentCoords) < #(b - currentCoords)
end)

-- nearest coordinate is now first
SetEntityCoords(PlayerPedId(), randomCoords[1])

Thanks, I will test and answer you

tw my friend

This would be the correct way to do it, since I didn’t add a check to get the closest one in the radius.

You win this time, Indra :frowning:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.