MathUtils.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. namespace FL
  4. {
  5. public static class MathUtils
  6. {
  7. /// <summary>
  8. /// 传递一个概率值(1-10000),返回随机结果是否在概率内
  9. /// </summary>
  10. /// <param name="probability">1-10000</param>
  11. /// <param name="maxExclusive">最大值</param>
  12. /// <returns></returns>
  13. public static bool Random(int probability, int maxExclusive = 10000)
  14. {
  15. //零固定返回false
  16. if (probability <= 0) return false;
  17. if (probability < maxExclusive)
  18. {
  19. var random = UnityEngine.Random.Range(0, maxExclusive);
  20. return random < probability;
  21. }
  22. return true;
  23. }
  24. /// <summary>
  25. /// 传递一个权重数组,返回随机结果对应的索引
  26. /// </summary>
  27. /// <param name="weights"></param>
  28. /// <returns></returns>
  29. public static int Random(IList<int> weights)
  30. {
  31. var total = 0;
  32. foreach (var weight in weights)
  33. {
  34. total += weight;
  35. }
  36. if (total <= 0)
  37. {
  38. return 0;
  39. }
  40. var random = UnityEngine.Random.Range(0, total);
  41. var temp = 0;
  42. for (var i = 0; i < weights.Count; i++)
  43. {
  44. temp += weights[i];
  45. if (random < temp)
  46. {
  47. return i;
  48. }
  49. }
  50. XGame.Log.Error($"随机数错误。total:{total} total:{random}");
  51. return 0;
  52. }
  53. }
  54. }