【发布时间】:2018-04-01 22:18:23
【问题描述】:
我是 Unity 的初学者。我正在创建一个随机产生三个潜在答案的教育蛇游戏。它正在工作,但是我不需要让它们彼此靠近。我也不需要在玩家/蛇附近产卵。有人已经尝试过帮助我,我向他寻求帮助,但似乎他无法解决问题,并且物体仍然彼此靠近。
void GeneratePotentialAnswers()
{
allAnswers.Clear();
List<Vector3> AnswerPositions = new List<Vector3>();
AnswerPositions.Add(player.transform.position);
for (int i = 0; i < potentialAnswers.Count; i++)
{
GameObject ans = Instantiate(enemyAnswerPrefab);
Vector3 pos;
int index = 0;
bool tooClose = false;
do
{
float rndWidth = Random.Range(15f, Screen.width - 25f);
float rndHeight = Random.Range(15f, Screen.height - 105f);
pos = Camera.main.ScreenToWorldPoint(new Vector3(rndWidth, rndHeight, 0f));
pos.z = -1f;
foreach (Vector3 p in AnswerPositions)
{
float distance = (pos - p).sqrMagnitude;
if (distance < 3f)
{
tooClose = true;
}
}
index++;
}
while (tooClose == true && index < 500);
Debug.Log(index);
AnswerPositions.Add(pos);
ans.transform.localPosition = pos;
ans.GetComponent<Answer>().potentialAnswer = potentialAnswers[i];
ans.GetComponent<Answer>().addToScore = scorePerCorrectAnswer;
ans.GetComponent<Answer>().SetAnswer();
allAnswers.Add(ans.GetComponent<Answer>());
}
}
【问题讨论】:
-
请编辑您的答案,以说明您和其他人迄今为止为调查您的问题所做的工作。您认为代码中的哪一行会导致问题?那个随机的
while循环在做什么? (它看起来像一个无限循环。)如果您使用相同的参数实例化所有对象,则期望类似的行为。确定位置的逻辑在哪里?就目前而言,这看起来像是一个“帮我解决这个问题”的问题,而不是一个“这是一个我不明白的错误”的问题。 -
@NonCreature0714 我是一个绝对的初学者,我真的不知道我在做什么。对不起,这个项目对我来说太难了,但我需要能够完成它。再次,我非常抱歉。我一个人呆着,不知道该怎么办。
-
也许尝试在网格而不是连续范围内生成坐标?