【问题标题】:Spawning Random GameObjects in Unity with Percentage/Probability [duplicate]以百分比/概率在 Unity 中生成随机游戏对象 [重复]
【发布时间】:2021-02-14 14:54:56
【问题描述】:

所以我有 4 个当前随机生成的游戏对象。

1.普通平台 2.尖顶平台 3.弹跳平台 4.币平台

所以问题在于它是随机生成的。 问题 如何添加或控制每个平台的生成概率。代码明智。 C#

喜欢在播放时间的 10 秒内。 85% 几率生成普通平台 5% 的几率生成尖顶平台 5% 的几率生成弹力平台 5%的几率生成币平台

请注意,平台在游戏中每秒钟都会生成一次。

【问题讨论】:

    标签: c# unity3d game-development


    【解决方案1】:

    你可以这样做。

    /// <summary>
    /// Returns random index of a finite probability distribution array
    /// </summary>
    /// <param name="prob"></param>
    /// <returns></returns>
    public static int PickOne(float[] prob)
    {
        int index = 0;
        float r = UnityEngine.Random.value;
    
        while (r > 0)
        {
            r -= prob[index];
            index++;
        }
        index--;
    
        return index;
    }
    

    这为您提供了一个基于概率分布的随机索引和最终支持。所以如果你打电话

    int index = PickOne(new float[] { 0.85f, 0.05f, 0.05f, 0.05f });
    

    index 将是基于您给出的概率分布的随机索引值(在本例中介于 0 和 3 之间)。

    【讨论】:

      猜你喜欢
      • 2021-02-06
      • 2017-10-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2017-03-24
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多