1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-23 02:18:47 +00:00

(#35) Add Random.NextUnitVector3

This commit is contained in:
Oliver Booth 2021-03-09 18:03:32 +00:00
parent f05e8537bd
commit 72e24aa791

View File

@ -31,6 +31,33 @@ namespace X10D.RandomExtensions
return new Vector2(x, y); return new Vector2(x, y);
} }
/// <summary>
/// Returns a <see cref="Vector3" /> with magnitude 1 whose components indicate a random point on the unit sphere.
/// </summary>
/// <param name="random">The <see cref="System.Random" /> instance</param>
/// <returns>
/// A <see cref="Vector3" /> whose <see cref="Vector3.Length()" /> returns 1, and whose components indicate a random
/// point on the unit sphere.
/// </returns>
public static Vector3 NextUnitVector3(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 z = seededRandom.NextSingle(-1, 1);
var mp = MathF.Sqrt(1 - z * z);
var x = mp * MathF.Cos(angle);
var y = mp * MathF.Sin(angle);
return new Vector3(x, y, z);
}
} }
} }