RandomMath.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //-----------------------------------------------------------------------------
  2. // RandomMath.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using Microsoft.Xna.Framework;
  9. namespace NetRumble
  10. {
  11. /// <summary>
  12. /// Static methods to assist with random-number generation.
  13. /// </summary>
  14. static public class RandomMath
  15. {
  16. /// <summary>
  17. /// The Random object used for all of the random calls.
  18. /// </summary>
  19. private static Random random = new Random();
  20. public static Random Random
  21. {
  22. get { return random; }
  23. }
  24. /// <summary>
  25. /// Generate a random floating-point value between the minimum and
  26. /// maximum values provided.
  27. /// </summary>
  28. /// <remarks>This is similar to the Random.Next method, substituting singles
  29. /// for integers.</remarks>
  30. /// <param name="minimum">The minimum value.</param>
  31. /// <param name="maximum">The maximum value.</param>
  32. /// <returns>A random floating-point value between the minimum and maximum v
  33. /// alues provided.</returns>
  34. public static float RandomBetween(float minimum, float maximum)
  35. {
  36. return minimum + (float)random.NextDouble() * (maximum - minimum);
  37. }
  38. /// <summary>
  39. /// Generate a random direction vector.
  40. /// </summary>
  41. /// <returns>A random direction vector in 2D space.</returns>
  42. public static Vector2 RandomDirection()
  43. {
  44. float angle = RandomBetween(0, MathHelper.TwoPi);
  45. return new Vector2((float)Math.Cos(angle),
  46. (float)Math.Sin(angle));
  47. }
  48. /// <summary>
  49. /// Generate a random direction vector within constraints.
  50. /// </summary>
  51. /// <param name="minimumAngle">The minimum angle.</param>
  52. /// <param name="maximumAngle">The maximum angle.</param>
  53. /// <returns>
  54. /// A random direction vector in 2D space, within the constraints.
  55. /// </returns>
  56. public static Vector2 RandomDirection(float minimumAngle, float maximumAngle)
  57. {
  58. float angle = RandomBetween(MathHelper.ToRadians(minimumAngle),
  59. MathHelper.ToRadians(maximumAngle)) - MathHelper.PiOver2;
  60. return new Vector2((float)Math.Cos(angle),
  61. (float)Math.Sin(angle));
  62. }
  63. }
  64. }