【问题标题】:Instantiate prefab at random X and Y while not spawning on top of each other在随机 X 和 Y 处实例化预制件,而不是在彼此之上生成
【发布时间】:2018-01-11 11:24:31
【问题描述】:

所以我正在为学校开发一款游戏,一款无尽的垂直平台游戏。我遇到的问题是我可以毫无问题地生成平台,但我似乎无法弄清楚如何让它们在彼此重叠时移动或摧毁。

public void SpawnPlatforms(float floatValue)
{
    yPos = spawnPlatformsTo;     
        while (yPos <= floatValue)
        {

            xPos = Random.Range(-4.5f, 4.5f);
            Vector2 posXY = new Vector2(xPos, yPos);


            var platformInstatiated = Instantiate(platforms[Random.Range(0, 2)], posXY, Quaternion.identity);

                platformInstatiated.transform.parent = GameObject.Find("Platforms").transform;
                platformInstatiated.localScale = new Vector3(Random.Range(.3f, 1f), 1, 1);

            yPos += Random.Range(1f, 1.75f);
        }

    spawnPlatformsTo = floatValue;
}

任何帮助都将不胜感激。

【问题讨论】:

  • 你不应该给你的变量类型 var,这是不好的做法,最好给它实际的对象类型。在这种情况下,platformInstatiated 应该是 GameObject。
  • 有趣。我不知道,谢谢你的提示。请问为什么这被认为是不好的做法?
  • 这只是命名约定的一部分。它有助于减少阅读和理解源代码所需的工作量。例如,不熟悉统一但使用 C# 的程序员不会知道 Instantiate 返回类型 GameObject,但这只是众多原因之一。这与您使用 PascalCase 方法和 camelCase 变量的原因相同。
  • 完美。很高兴知道,非常感谢。我在学校学习视频游戏设计,而不是编程,所以这对我来说有点新鲜。欣赏它。

标签: c# unity3d


【解决方案1】:

Unity 有一个名为 Bounds.Intersects 的函数。

将所有平台添加到列表中,或循环浏览场景中的所有平台,然后使用

检查每个平台
    //Fetch the Bounds from the Looped GameObject
    Bounds m_Bounds = loopedGameObject.GetComponent<Collider>().m_Collider.bounds;

    if(m_Bounds.Intersects(platformInstatiated.GetComponent<Collider>().bounds)
        Destroy(platformInstatiated);
        //Although you should really try to give it a new position instead of destroying it.

【讨论】:

  • 对不起,如果我问的是愚蠢的问题,我将如何将所有实例化的对象添加到列表中?
  • 我能够使用 for 循环将它们放入列表中。该列表打印出正确的计数。您发布的代码虽然不起作用。特别是这段代码Bounds m_Bounds = loopedGameObject.GetComponent&lt;Collider&gt;().m_Collider.bounds; 它是一个列表,所以 loopedGameObject 不起作用,结尾 m_collider.bounds 也不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
  • 2017-02-22
  • 2017-04-09
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
相关资源
最近更新 更多