12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- using System;
- using System.Collections.Generic;
- namespace FL
- {
- public static class MathUtils
- {
- /// <summary>
- /// 传递一个概率值(1-10000),返回随机结果是否在概率内
- /// </summary>
- /// <param name="probability">1-10000</param>
- /// <param name="maxExclusive">最大值</param>
- /// <returns></returns>
- public static bool Random(int probability, int maxExclusive = 10000)
- {
- //零固定返回false
- if (probability <= 0) return false;
- if (probability < maxExclusive)
- {
- var random = UnityEngine.Random.Range(0, maxExclusive);
- return random < probability;
- }
- return true;
- }
- /// <summary>
- /// 传递一个权重数组,返回随机结果对应的索引
- /// </summary>
- /// <param name="weights"></param>
- /// <returns></returns>
- public static int Random(IList<int> weights)
- {
- var total = 0;
- foreach (var weight in weights)
- {
- total += weight;
- }
- if (total <= 0)
- {
- return 0;
- }
- var random = UnityEngine.Random.Range(0, total);
- var temp = 0;
- for (var i = 0; i < weights.Count; i++)
- {
- temp += weights[i];
- if (random < temp)
- {
- return i;
- }
- }
- XGame.Log.Error($"随机数错误。total:{total} total:{random}");
- return 0;
- }
- }
- }
|