【问题标题】:Change gameobjects position if it's already used by a different gameobject?如果它已被不同的游戏对象使用,则更改游戏对象的位置?
【发布时间】:2022-01-20 23:56:42
【问题描述】:

游戏对象在某些平台对象上随机生成。我想避免这两个不同的游戏对象在同一个确切位置产生(money2 应该改变它的位置)。

代码如下:

void Start()
{
    int randMoney = Random.Range(0, 8);
    Vector3 moneyPos = transform.position;
    moneyPos.y += 0.5f;
    if (randMoney < 1)
    {
        GameObject moneyInstance = Instantiate(money, moneyPos, money.transform.rotation);
        moneyInstance.transform.SetParent(gameObject.transform);
    }

    int randMoney2 = Random.Range(0, 8);
    Vector3 money2Pos = transform.position;
    money2Pos.y += 0.5f;
    if (randMoney2 < 1)
    {
        GameObject money2Instance = Instantiate(money2, money2Pos, money2.transform.rotation);
        money2Instance.transform.SetParent(gameObject.transform);
    }

    if (money2Pos == moneyPos)
    {
        //where gameobject2s position should change
    }
}

感谢您抽出宝贵时间!

【问题讨论】:

  • 检查位置是否相同/太接近并继续选择一个新的随机位置,直到找到一个空闲的位置?
  • 哦,我想现在我明白了 .. 只需检查第一个硬币是否已经生成,然后跳过第二部分 .. 我认为这就是您要问的对吗?
  • 是的,完全正确。感谢您的回复!

标签: c# android unity3d position gameobject


【解决方案1】:

你在这里多次尝试做同样的事情。首先,money1 和money2 的代码块即使不完全相同也是相似的。考虑创建一个这样的函数:

public GameObject SpawnMoney(GameObject moneyPrefab, int spawnProbability, Vector3 spawnOffset)
{
    int spawnPourcentage = Random.Range(0, 101); // 101 because the random is exclusive
    bool willSpawn = spawnPourcentage <= spawnProbability;
    //if not supposed to spawn, then do nothing
    if(!willSpawn) return null;

    //Spawn effectively the money with position offset
    Vector3 plateformePosition = transform.position;
    GameObject moneyInstance = Instantiate(moneyPrefab, plateformePosition + spawnOffset, Quaternion.identity, transform);

    //return the instance if you want to manipulate it later ;)
    return moneyInstance;
}

现在你已经准备好运行你的函数了,如果你愿意,你可以在开始甚至循环中生成你的硬币!

如果有问题请追问

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多