Unity2D - 随机实例化的对象不需要彼此靠近地生成

时间:2018-04-01 22:18:24

标签: c# unity3d

我是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>());
    }
}

1 个答案:

答案 0 :(得分:0)

<强>答案

  1. 手动放置充当生成点的游戏对象,将SpawnPoint脚本附加到每个游戏对象。
  2. 当放置答案时,让所选spawnpoint的SpawnPoint脚本使用SphereCastAll检查附近区域是否空闲,如果不是,则应选择另一个生成点,直到找到一个免费生成点。
  3. 找到免费的spawnpoint时,在其位置实例化答案。
  4. <强>精化

    一个简单的解决方案是拥有一个SpawnPoint脚本。这是一个脚本放在你手动放置的一组个别生成点上,在地图的不同点可能有20个。

    然后,SpawnPoint脚本可以使用SphereCastAll方法,该方法以球形的形式收集给定大小的区域中的碰撞器集合。 (应该在3d中工作但可能不是2d,在这种情况下找到另一种类型而不是SphereCastAll。)

    以下是有关如何制作SphereCastAll的文档,请注意您可以设置球投的半径。

    https://docs.unity3d.com/ScriptReference/Physics.SphereCastAll.html

    如果SphereCastAll触发任何对象,它们将存储在返回的RaycastHit []中。你可以搜索一下,每个RaycastHit都会引用它碰到的对撞机,以及该对撞机的GameObject。这意味着您有一个区域内所有对象的列表。

    然后,您可以检查这些对象,看看它们是播放器还是其他答案。

    以下是RaycastHit的文档。

    https://docs.unity3d.com/ScriptReference/RaycastHit.html

    请注意,要获得对spawnpoints的访问权限,有一个列表或者可以为您选择一个的管理器脚本是很有用的。

相关问题