Heads or Tails? Flipping a coin
How do you flip a coin? In code? Elegantly?
I don’t mean the model, but returning a random boolean value?
Well, it’s not that simple… or, really… it is.
I needed a quick bit of code to get a random range for what is essentially Heads or Tails, and I felt that Random.Range (0, 2); and then testing this somehow was a bit ugly.
This seemed a bit more elegant:
bool orientation = (Random.value > 0.5f);
Random.value returns a random float number between 0.0 [inclusive] and 1.0 [inclusive], so we simply need to check whether it’s greater or less than a 50% chance of the returned value, or 0.5f.
http://docs.unity3d.com/Documentation/ScriptReference/Random-value.html
The Random class includes a few other goodies that can be used in clever ways…
http://docs.unity3d.com/Documentation/ScriptReference/Random.html
… but we’ll get to that soon enough.
No Comments