用一行C#代码随机生成1或-1:
static int f(Random r) { return (r.Next() & 2) - 1; }
这个是Milo Yip大神在知乎上的回答。
在unity中时,注意命名空间为:using System;
// 随机生成1 或 -1
static int GetOneOrMinusOne(System.Random r)
{
return (r.Next() & 2) - 1;
}
呵呵,想到一个更简单的方法:
float x = Random.value < 0.5f ? -1f : 1f;