Get a random position in area for ped spawn

Is there are any way how can I spawn peds at random position? Ofcourse I can just use random numbers for x y z but the problem is that ped could be spawned inside building for example? Also I am very interested how rockstar randomly founds coords for attacking peds on gtao missions for example. Could somebody help me with that?

You can use GetClosestRoad native
https://runtime.fivem.net/doc/natives/#_0x132F52BBA570FE92

1 Like

You could set up an array of locations that could be places to be spawned and then use math.random() to do a random of those values and put this in :

AddEventHandler("playerSpawed", function()
   -- other spawn code here
end
2 Likes

As I said math.random can create a situation when ped will be spawned inside building/object.

well not if you do it the way i say.

An example

local spawnLocations = 
{
    [1] = {x = 2.42334, y = 13.1312, z = -12.4312},
    [2] = {x = 2.433234, y = 13.134562, z = -12.4312},
    [3] = {x = 2.2221111134, y = 13.132, z = -12.4312},
    [4] = {x = 2.42334, y = 13.132, z = -12.4312},
    [5] = {x = 2.43333333234, y = 13.132, z = -12.4312},
    [6] = {x = 2.4331234, y = 13.132, z = -12.4312},
    [7] = {x = 2.3, y = 13.132, z = -12.4312},
}
    
print(spawnLocations[math.random(1, #spawnLocations)].x)

Or if you want a function for it you can do like :

local spawnLocations = 
{
    [1] = {x = 2.42334, y = 13.1312, z = -12.4312},
    [2] = {x = 2.433234, y = 13.134562, z = -12.4312},
    [3] = {x = 2.2221111134, y = 13.132, z = -12.4312},
    [4] = {x = 2.42334, y = 13.132, z = -12.4312},
    [5] = {x = 2.43333333234, y = 13.132, z = -12.4312},
    [6] = {x = 2.4331234, y = 13.132, z = -12.4312},
    [7] = {x = 2.3, y = 13.132, z = -12.4312},
}
    

function getRandomLocation(variable)
    return variable[math.random(1, #variable)]
end

local coords = getRandomLocation(spawnLocations)

print(coords.x)

--or 

print(getRandomLocation(spawnLocations).x)

As you can see there are a ton of ways to do it, you just set the needed coords in the variable and this creates the magic.

1 Like

This is not a fully random thing. You just select position from PRE-SET positions list.

2 Likes

Ok, so what do you think will happen if you do randomized coordinates. They will never fit any location and will spawn you either inside, over, under or outsite objects and the base of the world. Why not pick coorinates that will actually work. This is EXACTLY the way gta V or fiveM does it. It takes PRE-SET coordinates and randomizes the coordinates of the spawn of the player.

1 Like

Nvrm. Already done it with help of navmeshes and roads. Btw thanks for help. And here is my answer why I don’t want to use pre-set coords: It is just insane to create spawnpoints for the whole map or at least city. I am creating some kind of ‘gangs dispatch’ system. Like cops works now.

1 Like

+1 ! gg

how did you get this done?

just use GetClosestRoad Native