Ran*_*ant 4 c# scripting geometry unity-game-engine
我正在尝试在Unity中开发一个游戏,你可以从2D行星跳到2D行星,每个游戏都有自己的引力(游戏是2.5D,技术上,但所有的移动都沿着X和Y轴).我想使用参数公式将地雷放在这些行星的随机点上; 这是我开发的用于将它们附加到父Planet对象的脚本.然而,如预期的那样,地雷没有出现在圆圈表面,而是形状非常扭曲.我可能做错了什么?
public class LandMine : MonoBehaviour
{
public GameObject mine;
private GameObject landmine;
private System.Random rand;
private Vector3 pos;
List<GameObject> mines;
public void Start()
{
mines = new List<GameObject>();
LevelStart();
}
public Vector3 ran()
{
rand = new System.Random(359);
float angle = rand.Next();
float value = angle * (Mathf.PI/180f);
float x = (float) (0.5000001 * Mathf.Cos(value)) + 6;
float y = (float) (0.5000001 * Mathf.Sin(value)) - 9;
return new Vector3(x,y,0);
}
void LevelStart()
{
for (int i = 0; i < 5; i++)
{
pos = ran;
mine = Instantiate(mine, pos,Quaternion.identity) as GameObject;
mines.Add(mines);
}
foreach (GameObject m in mines)
{
m.transform.parent = this.transform;
}
}
}
Run Code Online (Sandbox Code Playgroud)
传递给Random构造函数的参数是随机种子,而不是数字范围.如果要在每次启动游戏时生成新的随机数,请使用无参数构造函数.此外,仅声明随机数生成器一次.它使用时钟来初始化自身,但由于时钟非常慢(与CPU时钟频率相比),如果每次创建一个新实例,它可能会多次生成相同的随机数.
static readonly Random random = new Random();
Run Code Online (Sandbox Code Playgroud)
然后生成一个新的角度
int angle = random.Next(360); // generates numbers in the range 0 ... 359
Run Code Online (Sandbox Code Playgroud)
要么
double angle = 2.0 * Math.PI * random.NextDouble();
Run Code Online (Sandbox Code Playgroud)
矿井坐标的公式是
mineX = centerX + radius * cos(angle)
mineY = centerY + radius * sin(angle)
Run Code Online (Sandbox Code Playgroud)