Intersection Checking

From XNAWiki
Jump to: navigation, search

Point and an axis-aligned BoundingBox

/// <summary>
/// Check if a point lies inside a <see cref="BoundingBox"/>
/// </summary>
/// <param name="point">3D Point</param>
/// <param name="box">Bounding box</param>
/// <returns>True if point lies inside the bounding box</returns>
public static bool PointInsideBoundingBox(Vector3 point, BoundingBox box)
{
    if (point.X < box.Min.X)
        return false;
 
    if (point.Y < box.Min.Y)
        return false;
 
    if (point.Z < box.Min.Z)
        return false;
 
    if (point.X > box.Max.X)
        return false;
 
    if (point.Y > box.Max.Y)
        return false;
 
    if (point.Z > box.Max.Z)
        return false;
 
    // Point must be inside box
    return true;
}

Point and a Cone

/// <summary>
/// Check if a point lies inside a conical region. Good for checking if a point lies in something's
/// field-of-view cone.
/// </summary>
/// <param name="point">Point to check</param>
/// <param name="coneOrigin">Cone's origin</param>
/// <param name="coneDirection">Cone's forward direction</param>
/// <param name="coneAngle">Cone's theta angle (radians)</param>
/// <returns>True if point is inside the conical region</returns>
public static bool PointInsideCone(Vector3 point, Vector3 coneOrigin, Vector3 coneDirection,
                                   double coneAngle)
{
    Vector3 tempVect = Vector3.Normalize(point - coneOrigin);
 
    return Vector3.Dot(coneDirection, tempVect) >= Math.Cos(coneAngle);
}

Point and a Sphere

/// <summary>
/// Check if a point lies inside of a <see cref="BoundingSphere"/>.
/// </summary>
/// <param name="point">3D Point</param>
/// <param name="sphere">Sphere to check against</param>
/// <returns>True if point is inside of the sphere</returns>
public static bool PointInsideBoundingSphere(Vector3 point, BoundingSphere sphere)
{
    Vector3 diffVect = point - sphere.Center;
 
    return (diffVect.LengthSquared() < (float)Math.Abs(sphere.Radius * sphere.Radius));
}