I’m attempting to create an algorithm to automatically instantiate objects. I’d like the objects to have a pretty big y-index difference, to make it more difficult for players to finish the level. However, I can’t seem to create such a simple thing. It could be a lack of my C# knowledge, a lack of math knowledge, or my brains are not working like they should at this moment! Hah.
Anyway, I’ve got the example of my script here. I hope you’ll get the idea of it. If not, I’ll explain it below the script.
disY = Random.Range(-6, -10);
if (disY == ldisY)
{
disY = Random.Range(-6, -10);
}
else if (disY < -8.9 && disY > -8)
{
disY = Random.Range(-9, -10);
}
else if (ldisY < -8 && disY < -8)
{
disY = Random.Range(-8, -10);
}
else if (ldisY < -8 && disY > -8)
{
disY = Random.Range(-6, -8);
}
//@ end of function
ldisY = disY;
*Note this is in a loop which will be run 30 times. I’d like 30 objects to be instantiated.
The idea is to have a bigger distance between the y-index’s. Of course a little difference between objects may occur, but I’d like to make it more of a challange. There should be a difference between 1 and 4 pixels (these values are pixels) all the time. But most of the time the y-index of every object is pretty close to each other.
So how would I make an algorithm that has a bigger difference, so the y-index will not be close to eachother. To make the question more clear, I’ve created a simple painting.
I am doing this manually so try and it and will see
float previousY = Random.Range(minValue,maxValue);
// Instantiate first one
// Start looping for 29 next
for (int i = 1; i < 30 ; i++)
{
// Get a random value based on the previous one
// The result will be between 1 and 4 bigger than the previous
float y = Random.Range(previousY + 1f, previousY + 4f);
// Randomly invert the sign so that it goes up and down
int sign = Random.Range(0,2);
if(sign == 0) y *= -1;
// Constrain the value within a range so that it does not get out of screen
float check = y + previousY;
if(check > maxValue) y *= -1;
if(check < minValue) y *= -1;
// Instantiate object
// Place the y value for next round
previousY = y;
}
I see that your range is always 2, so what you can do here is after a random occurs, change the range from next one such a way that it excludes the first generated y. For example see the code below,