123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- 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;
- }
- /// <summary>
- /// 毫秒转指定格式的时间字符串
- /// </summary>
- /// <param name="milliseconds"></param>
- /// <param name="format">字符串格式, 例: @"mm\:ss"</param>
- /// <returns></returns>
- public static string ToTimeString(this long milliseconds, string format)
- {
- var timeData = TimeSpan.FromMilliseconds(milliseconds);
- return timeData.ToString(format);
- }
- }
- }
|