Randomization

From XNAWiki
Jump to: navigation, search

Get Random number within a min/max range

/// <summary>
/// Returns a number between two values.
/// </summary>
/// <param name="min">Lower bound value</param>
/// <param name="max">Upper bound value</param>
/// <returns>Random number between bounds.</returns>
public static float RandomBetween(double min, double max)
{
    Random random = new Random();
    return (float)(min + (float)random.NextDouble() * (max - min));
}

Get a Random number with a 50% chance of being either -1 or 1

This function requires the RandomBetween() function, shown at the top of this page

/// <summary>
/// 50/50 chance of returning either -1 or 1
/// </summary>
public static int Random5050
{
    Random random = new Random();
 
    get
    {
        if (RandomBetween(0, 2) >= 1)
            return 1;
        else
            return -1;
    }
}

Chance in Percentage

public static bool Chance(int percentage)
{
    Random random = new Random();
 
    double chance = percentage + random.Next(1, 100);
 
    if (chance >= 100)
    {
        return true;
    }
 
    return false;
}


Create a random point in 3D space

This function requires the RandomBetween() function, shown at the top of this page

public static Vector3 RandomPosition(Vector3 minBoxPos, Vector3 maxBoxPos)
{
    Random random = new Random();
 
    return new Vector3(
             RandomBetween(minBoxPos.X, maxBoxPos.X), 
             RandomBetween(minBoxPos.Y, maxBoxPos.Y), 
             RandomBetween(minBoxPos.Z, maxBoxPos.Z));
}

Create a random direction in any direction in 3D space

This function requires the RandomBetween() function, shown at the top of this page


public static Vector3 RandomDirection()
{
    Random random = new Random();
 
    Vector3 direction = new Vector3(
            RandomBetween(-1.0f, 1.0f), 
            RandomBetween(-1.0f, 1.0f), 
            RandomBetween(-1.0f, 1.0f));
    direction.Normalize();
 
    return direction;
}

http://mathworld.wolfram.com/SpherePointPicking.html

Get a Random point on a triangle whose points lie in 3D space

/// <summary>
/// Helper function chooses a random location on a triangle.
/// </summary>
public static Vector3 PickRandomPoint(
          Vector3 position1, 
          Vector3 position2, 
          Vector3 position3)
{
    Random random = new Random();
 
    float a = (float)random.NextDouble();
    float b = (float)random.NextDouble();
 
    if (a + b > 1)
    {
        a = 1 - a;
        b = 1 - b;
    }
 
    return Vector3.Barycentric(position1, position2, position3, a, b);
}