1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-22 20:58:48 +00:00

(#35) Add Random.NextUnitVector2

Returns a point which lies on the unit circle
This commit is contained in:
Oliver Booth 2021-03-09 17:36:55 +00:00
parent 6860afd4f9
commit f05e8537bd
2 changed files with 38 additions and 1 deletions

View File

@ -0,0 +1,37 @@
#if NET5_0
using System;
using System.Numerics;
using X10D.SingleExtensions;
namespace X10D.RandomExtensions
{
public static partial class RandomExtensions
{
/// <summary>
/// Returns a <see cref="Vector2" /> with magnitude 1 whose components indicate a random point on the unit circle.
/// </summary>
/// <param name="random">The <see cref="System.Random" /> instance</param>
/// <returns>
/// A <see cref="Vector2" /> whose <see cref="Vector2.Length()" /> returns 1, and whose components indicate a random
/// point on the unit circle.
/// </returns>
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

View File

@ -10,7 +10,7 @@ namespace X10D.RandomExtensions
/// <summary>
/// Extension methods for <see cref="System.Random" />.
/// </summary>
public static class RandomExtensions
public static partial class RandomExtensions
{
internal static readonly Random Random = new();