02.03.2019, 21:21
Your function will always return the same value because it loops through all of them, sets the spawnid and then continues with the loop. This happens once for all entries so the last one will get chosen.
Another problem is that you don't save whether or not a spawn is taken already. You need to make a list of currently unoccupied spawns and then choose a random one from the list.
Something like this
Make sure to check if this function returns -1 where you use it. In that case no spawn was found and you could delay the spawn or choose a random one anyway.
You could also use dynamic areas for this. Create one for each spawn and instead of looping through all players just use CountPlayersInDynamicArea to determine whether or not it is occupied.
This would be a lot more efficient as well as CountPlayersInDynamicArea does not loop through all players again and again (it counts the players as they enter and leave the areas).
You probably want to add checks for virtual world, interior and if the player is actually in the event to the above loop as well.
Another problem is that you don't save whether or not a spawn is taken already. You need to make a list of currently unoccupied spawns and then choose a random one from the list.
Something like this
PHP код:
EventSpawn()
{
new spawns[sizeof(EventSpawns)], count = 0;
for(new sid = 0; sid < sizeof(EventSpawns); sid++)
{
new bool:occupied = false;
foreach(new i : Player) // Loop through all players and check if any of them is near the spawn
{
if(IsPlayerInRangeOfPoint(i, 1.0, EventSpawn[sid][0], EventSpawn[sid][1], EventSpawn[sid][2]))
{
occupied = true; // This spawn is occupied, set the variable to true and stop the loop
break;
}
}
if(!occupied) // This spawn is not occupied since no player was found earlier, so add it to the list and increase the counter
{
spawns[count] = sid;
count ++;
}
}
if(count == 0) // All spawns are occupied, decide what to do in this case
{
return -1;
}
return spawns[random(count)]; // Return a random unoccupied spawn from the list
}
You could also use dynamic areas for this. Create one for each spawn and instead of looping through all players just use CountPlayersInDynamicArea to determine whether or not it is occupied.
This would be a lot more efficient as well as CountPlayersInDynamicArea does not loop through all players again and again (it counts the players as they enter and leave the areas).
You probably want to add checks for virtual world, interior and if the player is actually in the event to the above loop as well.