Newer
Older
DungeonShooting / DungeonShooting_Godot / src / framework / common / Utils.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using Godot;
  4.  
  5. /// <summary>
  6. /// 常用函数工具类
  7. /// </summary>
  8. public static class Utils
  9. {
  10.  
  11. private static readonly Random _random;
  12. static Utils()
  13. {
  14. _random = new Random();
  15. }
  16. /// <summary>
  17. /// 返回随机 boolean 值
  18. /// </summary>
  19. public static bool RandomBoolean()
  20. {
  21. return _random.NextSingle() >= 0.5f;
  22. }
  23.  
  24. /// <summary>
  25. /// 返回一个区间内的随机小数
  26. /// </summary>
  27. public static float RandomRangeFloat(float min, float max)
  28. {
  29. if (min == max) return min;
  30. if (min > max)
  31. return _random.NextSingle() * (min - max) + max;
  32. return _random.NextSingle() * (max - min) + min;
  33. }
  34.  
  35. /// <summary>
  36. /// 返回一个区间内的随机整数
  37. /// </summary>
  38. public static int RandomRangeInt(int min, int max)
  39. {
  40. if (min == max) return min;
  41. if (min > max)
  42. return Mathf.FloorToInt(_random.NextSingle() * (min - max + 1) + max);
  43. return Mathf.FloorToInt(_random.NextSingle() * (max - min + 1) + min);
  44. }
  45.  
  46. /// <summary>
  47. /// 随机返回其中一个参数
  48. /// </summary>
  49. public static T RandomChoose<T>(params T[] list)
  50. {
  51. if (list.Length == 0)
  52. {
  53. return default;
  54. }
  55.  
  56. return list[RandomRangeInt(0, list.Length - 1)];
  57. }
  58.  
  59. /// <summary>
  60. /// 随机返回集合中的一个元素
  61. /// </summary>
  62. public static T RandomChoose<T>(List<T> list)
  63. {
  64. if (list.Count == 0)
  65. {
  66. return default;
  67. }
  68.  
  69. return list[RandomRangeInt(0, list.Count - 1)];
  70. }
  71.  
  72. /// <summary>
  73. /// 随机返回集合中的一个元素, 并将其从集合中移除
  74. /// </summary>
  75. public static T RandomChooseAndRemove<T>(List<T> list)
  76. {
  77. if (list.Count == 0)
  78. {
  79. return default;
  80. }
  81.  
  82. var index = RandomRangeInt(0, list.Count - 1);
  83. var result = list[index];
  84. list.RemoveAt(index);
  85. return result;
  86. }
  87. /// <summary>
  88. /// 根据四个点计算出矩形
  89. /// </summary>
  90. public static Rect2 CalcRect(float start1, float end1, float start2, float end2)
  91. {
  92. return new Rect2(
  93. Mathf.Min(start1, start2), Mathf.Min(end1, end2),
  94. Mathf.Abs(start1 - start2), Mathf.Abs(end1 - end2)
  95. );
  96. }
  97. }