I have a Poisson Disk Sampling algorithm in my game, which I use for object generation. I use a while loop in the algorithm, which makes it very slow. How could I increase the speed of my algorithm?

Here’s the loop code:

while #spawnPoints > 0 do
-- Run some code here to generate points.
runService.Heartbeat:Wait()
end

Because of this loop, it takes long to generate objects on my map.

Depending on the length of the code, you could probably spawn many, many points per heartbeat. You could play around with a limit, such as 100, and only end that heartbeat’s code after spawning 100 (or the remaining number) of points.

Another thing to consider is if you can pre-calculate some of the Poisson Disk Sampling Algorithm. Does all of it really need to happen at run time? Maybe you could have a very large library of squares or zones, which have a list of pre-generated points from a prior run of the Sampling Algorithm. Here’s an example:

Run the Sampling Algorithm 10,000 times.

After each run, record all the points in a table, datastore, etc.

At runtime, generate a random number from 1 to 10,000.

Use that number to index which prior run’s set of points to use for this instance’s objects.

Spawn objects at the set of points from that prior run.