1
\$\begingroup\$

I am trying to create procedural space background with a bunch of sprites of nebulas and stars. I have made few prefabs with different types of sprites attached to them. I have created an array through which game will loop and randomly place different stars on a background.

The question is. I want for example 90% of white stars in the background and 10% of others. I know I can create few loops for each prefab with a different maximum number, but it doesn't look very efficient. Is there any way to prioritize some array items while looping through an array?

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Decide your total star count. Divide it into segments. For example, out of 100 total stars:

  • 10 Blue Star Hard
  • 30 White Star Medium
  • 60 Red Star Soft

Code:

//can make enum StarColour
int BLUE = 0;
int WHITE = 1;
int RED = 2;

//can make enum StarFocus
int HARD = 0;
int MEDIUM = 1;
int SOFT = 2;

int i = 0;
for (i = 0; i < blueHardTotal; i++)
{
    PlaceStar(BLUE, HARD);
} 

for (i = blueHardTotal; i < blueHardTotal + whiteMediumTotal; i++)
{
    PlaceStar(WHITE, MEDIUM);
} 

for (i = whiteMediumTotal; i < whiteMediumTotal + redSoftTotal; i++)
{
    PlaceStar(RED, SOFT);
} 

This takes you through index [0] to [99] in segments. P.S. There is nothing inefficient about this; and if you make the Totals compile-time constants, then the compiler should unroll the loops, thereby avoiding all conditionals.

If you want a more elegant way:

int[,] totals; //index in here by colour and focus, e.g. totals[RED, SOFT]

int i = 0;
for (int c = 0; c < COLOUR_COUNT; c++)
{
    for (int f = 0; f < FOCUS_COUNT; f++)
    {
        int max = i + totals[c, f];
        while (i < max)
        {
            PlaceStar(c, f);
            i++;
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ Could you expand with this int[,] totals; and enums thing? I do not completely understand how can I create such array and mark each item with enums. \$\endgroup\$ – Random generalist Mar 19 '18 at 11:05
  • \$\begingroup\$ @NikitaDemidenko enum in C# is just a group of int under the hood. Every enum entry has a corresponding integer value, assigned from 0 upwards. You can easily cast the enum to an int e.g. int med = starFocus.Medium; and even back again. So in that sense it's exactly the same as using a group of pre-defined constants like I have above, but it gets to have a name and its own grouping - a bit like a C# namespace, really. Do a little research on stackoverflow and you'll understand. \$\endgroup\$ – Engineer Mar 19 '18 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.