From f05e8537bd637a203cabf40eba1997e1f7c22d88 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 9 Mar 2021 17:36:55 +0000 Subject: [PATCH] (#35) Add Random.NextUnitVector2 Returns a point which lies on the unit circle --- .../RandomExtensions.Numerics.cs | 37 +++++++++++++++++++ X10D/src/RandomExtensions/RandomExtensions.cs | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 X10D/src/RandomExtensions/RandomExtensions.Numerics.cs diff --git a/X10D/src/RandomExtensions/RandomExtensions.Numerics.cs b/X10D/src/RandomExtensions/RandomExtensions.Numerics.cs new file mode 100644 index 0000000..61fd8dc --- /dev/null +++ b/X10D/src/RandomExtensions/RandomExtensions.Numerics.cs @@ -0,0 +1,37 @@ +#if NET5_0 +using System; +using System.Numerics; +using X10D.SingleExtensions; + +namespace X10D.RandomExtensions +{ + public static partial class RandomExtensions + { + /// + /// Returns a with magnitude 1 whose components indicate a random point on the unit circle. + /// + /// The instance + /// + /// A whose returns 1, and whose components indicate a random + /// point on the unit circle. + /// + public static Vector2 NextUnitVector2(this Random random) + { + if (random is null) + { + throw new ArgumentNullException(nameof(random)); + } + + var seed = random.Next(); + var seededRandom = new Random(seed); + + var angle = seededRandom.NextSingle(0, 360).DegreesToRadians(); + var x = MathF.Cos(angle); + var y = MathF.Sin(angle); + + return new Vector2(x, y); + } + } +} + +#endif diff --git a/X10D/src/RandomExtensions/RandomExtensions.cs b/X10D/src/RandomExtensions/RandomExtensions.cs index 43c9504..088f685 100644 --- a/X10D/src/RandomExtensions/RandomExtensions.cs +++ b/X10D/src/RandomExtensions/RandomExtensions.cs @@ -10,7 +10,7 @@ namespace X10D.RandomExtensions /// /// Extension methods for . /// - public static class RandomExtensions + public static partial class RandomExtensions { internal static readonly Random Random = new();