- Home /
Random value from -1 to 1
I'm trying to generate random directions for enemies to move in using this code:
currentDirection = new Vector3(Random.value, 0, Random.value);
currentDirection.Normalize();
However, I really need those two random values to be positive or negative, and to decide randomly between the two. I tried doing
Random.value * Random.Range(-1,1)
for both of those, but it turned out to be giving me directions locked into 45 degree increments.
Is there another way I can get random +/- values into those two spots?
Thanks in advance.
Answer by Eric5h5 · Nov 17, 2011 at 05:43 AM
Random.Range(-1.0f, 1.0f)
See the docs for Random.Range. No need for Random.value.
Well, putting in the Random.value as well will make a distribution which clusters around the centre, so it'd be useful for that- except that it gets normalized at the end anyway. So yeah, doesn't do much in this case.
I'm dumb, thanks for pointing this out. Read the reference wrong and only saw the part mentioning it prints int from -1 to 1, which would be completely useless.
Thanks!
Right, since UnityScript is now a thing from the past we can change all examples to be C#. I'll edit this answer.
Answer by syclamoth · Nov 17, 2011 at 05:43 AM
How about
Vector2 flatDirection = Random.insideUnitCircle;
currentDirection = new Vector3(flatDirection.x, 0, flatDirection.y).normalized;