Check the facebook page!

If you prefer, you can also follow the Facebook page for this blog :)

Thursday 22 May 2014

The best part about programming is improvisation

That's right, programming requires a lot of creativity and active imagination, you can always come up with new ways to do things. Thinking outside the box and in non-conventional ways can help you come up with unique solutions to problems that might arise.

Here's the latest example of that that I had:





A few months ago I had a task to create a way to randomly spawn objects in specific positions so what came to my mind was to create a spawner object.

But then it was time to do the code and since each spawner would spawn a different object randomly of course, but the thing is, I didn't want every object to have the same odds of spawning.
For example, one of the spawners was meant to instantiate (spawn) different types of crystals (currency items) which were worth 1, 2 and 10 crystals respectively.

And this is where improvisation and creativity came in! Of course there is a piece of code which selects a random number between the values defined by you, but how would you easily choose the odds of each object without having to re-write the whole code?

This is what I came up with, I created a variable for each of the objects called "prefabxFrequency" which was an integer (a simple number with no decimals) and then I made another variable called "totalFrequency" which was the sum of all (3 in this case) frequencies.

So let's say prefab1Frequency = 1000, prefab2 = 500 and prefab3 = 100, for example, the "totalFrequency" would be 1600.

After that, I also made 2 other variables, "minTime" and "maxTime" to specify the frequency on when to spawn the items. I then used a Random.Range(minTime, maxTime); so that I wouldn't get a mess, and a randomer = Random.Range.(0, totalFrequency); to select a random number between 0 and the prefab frequency totals.
And then what I did (and this is where it all comes together) I created 3 conditions to figure out which object to spawn.

if(randomer <= frequency1) (in this case 1000)
 {
*code to instantiate the object here*
} else if (randomer >= frequency1 && randomer <= frequency2) {
*code to instantiate the second object*
}  else { (no need to calculate anything here, if not one of the first 2 then it's definitely the 3rd one)
*code to instantiate the last object*
}

And that is the beauty of programming, if you don't know a way of doing things, well, just create whatever works for you! Pretty much everything can be achieved through thousands, if not millions, of ways, you just got to think and see what works and what doesn't. Experiment and take chances, you might come into something big one day :P

Cheers!

PS: Don't be afraid to comment or anything of the sorts :)

No comments:

Post a Comment

What do you think or want to share?