XRandom
Random number generator with game-friendly methods.
using Xengine.Math;
Constructors
// Random seed
var random = new XRandom();
// Fixed seed (reproducible)
var seeded = new XRandom(12345);
Methods
Int
int Int(int min, int max)
Random integer between min (inclusive) and max (exclusive).
int dice = random.Int(1, 7); // 1 to 6
int index = random.Int(0, array.Length);
Float
float Float()
Random float between 0 and 1.
float chance = random.Float();
if (chance < 0.25f) // 25% chance
DropRareItem();
Float (range)
float Float(float min, float max)
float speed = random.Float(5f, 10f);
float angle = random.Float(0, 360);
Bool
bool Bool()
Random true or false (50% each).
bool heads = random.Bool();
Chance
bool Chance(float probability)
Returns true with given probability (0 to 1).
if (random.Chance(0.1f)) // 10% chance
SpawnBoss();
Vector2
Vector2 Vector2(float minX, float maxX, float minY, float maxY)
var pos = random.Vector2(-10, 10, -10, 10);
Vector3
Vector3 Vector3(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
var pos = random.Vector3(-10, 10, 0, 5, -10, 10);
UnitVector2
Vector2 UnitVector2()
Random direction in 2D (length = 1).
var direction = random.UnitVector2();
UnitVector3
Vector3 UnitVector3()
Random direction in 3D (length = 1).
var direction = random.UnitVector3();
velocity = direction * speed;
InsideUnitCircle
Vector2 InsideUnitCircle()
Random point inside a circle of radius 1.
var offset = random.InsideUnitCircle() * radius;
InsideUnitSphere
Vector3 InsideUnitSphere()
Random point inside a sphere of radius 1.
var pos = center + random.InsideUnitSphere() * radius;
Color
Color Color()
Random fully saturated color.
var color = random.Color();
Element
T Element<T>(IList<T> list)
Pick random element from list.
var enemy = random.Element(enemyTypes);
var spawnPoint = random.Element(spawnPoints);
Shuffle
void Shuffle<T>(IList<T> list)
Randomly reorder list elements.
random.Shuffle(deck);
Common Patterns
Random Spawning
var random = new XRandom();
for (int i = 0; i < 20; i++)
{
var pos = new Vector3(
random.Float(-10, 10),
0.5f,
random.Float(-10, 10)
);
var enemy = scene.CreateGameObject($"Enemy{i}", pos);
enemy.AddComponent<Enemy>();
}
Random Drops
void OnEnemyDeath()
{
if (random.Chance(0.3f)) // 30% drop chance
{
var loot = random.Element(lootTable);
SpawnItem(loot, position);
}
}
Particle Explosion
for (int i = 0; i < 50; i++)
{
var particle = scene.CreateGameObject("Particle", position);
var p = particle.AddComponent<Particle>();
p.Velocity = random.UnitVector3() * random.Float(5, 15);
p.Color = random.Color();
}