0
\$\begingroup\$

I have a 2D grid of cells in Unity, and each cell can be on or off. I want to randomly generate the on cells, and when I just assign a probability to each cell, the entire grid has the same density, looking something like this: enter image description here

But I would like different densities for random areas, something more like: enter image description here

Is there some kind of algorithm to make this random generation possible?

\$\endgroup\$
2
  • \$\begingroup\$ Have you looked into Mathf.PerlinNoise as a way to vary the spawn probability over space in a smoothly-varying way? \$\endgroup\$
    – DMGregory
    Commented Dec 28, 2023 at 2:27
  • \$\begingroup\$ In this answer I show how to use Poisson-Disk sampling to get a very similar result. That solution uses Perlin noise to guide the probability rate (much as DMGregory suggested). With some minor changes it could be adapted to use your on/off cell grid. Is that enough to address your question? \$\endgroup\$
    – Pikalek
    Commented Dec 28, 2023 at 3:30

2 Answers 2

2
\$\begingroup\$

Use Mathf.PerlinNoise todo it , example here:

float Perlin(float x, float y)
{
        for(x; x< ChunkSize; x++)
       {
                for(y; y < ChunkSize; y++)
                {
                        return Mathf.PerlinNoise(x,y);
                 }
         }
}

https://forum.unity.com/threads/mathf-perlinnoise-a-way-to-random-seed-it.336147/

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This code uses two for loops to return just a single value. Only the first and seventh line actually do anything. It may be better to tailor your example to the question that was asked, showing how to use Perlin noise to vary an on/off probability. \$\endgroup\$
    – DMGregory
    Commented Dec 28, 2023 at 12:17
0
\$\begingroup\$

You can just set the densities probability to each area so you will get result close to your second picture. Write the algorithm to separate the gird on areas. for example you have 8x8 grid and areas:

11122333
11122333
44422555
44466555 
44466555
77888888
77888888
77888888

Generate probablity for each area: 1)p=80% 2)p=30% 3)p=45% etc. And you can customize it for your needs.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This answer would be better if it detailed how to write such an algorithm. \$\endgroup\$
    – DMGregory
    Commented Dec 31, 2023 at 0:42
  • \$\begingroup\$ Sure I can but It will take 2 hours to write such algorithm and I don't know his project requirements so he will need to rewrite it anyway, I believe if person need such result he should be able to write such an algorithm by himself and he will learn more by doing it instead of copy paste the solution. \$\endgroup\$
    – Bogdan
    Commented Dec 31, 2023 at 19:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .