如何将3个游戏对象放置在随机位置范围内,而没有任何一个对象与其他2个对象具有相同的位置?我该如何实现?
到目前为止。
public GameObject[] sprites;
int[] Position = new int[3] { 0, 5, -5 };
int resultSprite1;
int resultSprite2;
int resultSprite3;
int y;
int z;
Vector3 pos;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
resultSprite1 = Position[Random.Range(0, Position.Length)];
y = 0;
z = 0;
pos = new Vector3(resultSprite1, y, z);
sprites[0].transform.position = pos;
resultSprite2 = Position[Random.Range(0, Position.Length)];
y = 0;
z = 0;
pos = new Vector3(resultSprite2, y, z);
sprites[1].transform.position = pos;
resultSprite3 = Position[Random.Range(0, Position.Length)];
y = 0;
z = 0;
pos = new Vector3(resultSprite3, y, z);
sprites[2].transform.position = pos;
}
}
如何实现此目的,以使两个对象之间没有相同的位置。它们都应该彼此独立。
谢谢。
答案 0 :(得分:1)
List<int> usedNumbers = new List<int> ();
void Update ()
{
if (Input.GetKeyDown (KeyCode.R))
{
//Since it works on update. You should clear the last list before creating a new one.
usedNumbers.Clear();
for (int i = 0; i < Position.Length; i++)
{
do
{
number = Random.Range (0, Position.Length);
} while (usedNumbers.Contains (number));
//You have your unique number here.
sprites[i].transform.position = new Vector3 (Position[number], 0f, 0f);
//Do not forget to store your number in usedNumbersList.
usedNumbers.Add (number);
}
}
}