Question by
mullac51 · Feb 13, 2017 at 01:45 PM ·
randomif-statementsrandom.rangeifif-else
Randomly choosing between 3 options
Basically i want the character to either jump up and left, up and right or just straight up.
Sorry if it' simple to do, i'm new to this
Here is my code so far:
if (Random.Range(0, 2) == 0)
rb.AddForce(Vector2.up * upforce, ForceMode2D.Impulse);
rb.AddForce(Vector2.left * directionforce, ForceMode2D.Impulse);
else
rb.AddForce(Vector2.up * upforce, ForceMode2D.Impulse);
rb.AddForce(Vector2.right * directionforce, ForceMode2D.Impulse);
else
rb.AddForce(Vector2.up * upforce, ForceMode2D.Impulse);
Comment
Best Answer
Answer by Chikari · Feb 13, 2017 at 01:57 PM
switch(Random.Range(0,3))
{
case 0:
rb.AddForce(Vector2.up * upforce, ForceMode2D.Impulse);
rb.AddForce(Vector2.left * directionforce, ForceMode2D.Impulse);
break;
case 1:
rb.AddForce (Vector2.up * upforce, ForceMode2D.Impulse);
rb.AddForce (Vector2.right * directionforce, ForceMode2D.Impulse);
break;
case 2:
rb.AddForce (Vector2.up * upforce, ForceMode2D.Impulse);
break;
}
Random.Range should be Random.Range(0,3) if you want it to reach the case 2. (int)Random.Range will exclude the max value.
No. See the documentation: "Returns a random float number between and $$anonymous$$ [inclusive] and max [inclusive]. "
It's odd, but correct.
For floats yes but not for integers, scroll down to the doc. In this case it is an int so it will exclude the max, if it was float it would hardly ever reach any case.
Thanks for the heads up! I have adjusted my answer.