Exemple #1
0
    /// <summary>
    /// Checks whether the two boxes collide, generating an intersection containing the collision data.
    /// This function can only compare bounding boxes againsts other bounding boxes.
    /// </summary>
    /// <param name="other">bounding box to check</param>
    /// <param name="intersection">the collision data, <code>null</code> if no collision has been detected.</param>
    /// <returns></returns>
    public override bool Intersects(DBoxCollider other, out Manifold intersection)
    {
        intersection = null;

        //check if one of them is a trigger
        if (this.IsTrigger || other.IsTrigger)
        {
            intersection = new Manifold(this.Body, other.Body);
            return(true);
        }

        // Vector from A to B
        Vector2F distance = other.Body.Position - Body.Position;

        // Calculate half extents along x axis for each object
        Fix32 xEntentA = (max.x - min.x) / (Fix32)2;
        Fix32 xExtentB = (other.max.x - other.min.x) / (Fix32)2;

        // Calculate overlap on x axis
        Fix32 offsetX = xEntentA + xExtentB - Fix32.Abs(distance.x);

        // SAT test on x axis
        if (offsetX > Fix32.Zero)
        {
            // Calculate half extents along x axis for each object
            Fix32 yExtentA = (max.y - min.y) / (Fix32)2;
            Fix32 yExtentB = (other.max.y - other.min.y) / (Fix32)2;

            // Calculate overlap on y axis
            Fix32 offsetY = yExtentA + yExtentB - Fix32.Abs(distance.y);

            // SAT test on y axis
            if (offsetY > Fix32.Zero)
            {
                Vector2F n;
                // Find out which axis is axis of least penetration
                if (offsetX < offsetY)
                {
                    // Point towards B knowing that n points from A to B
                    if (distance.x < Fix32.Zero)
                    {
                        n = new Vector2F(-1, 0);
                    }
                    else
                    {
                        n = new Vector2F(1, 0);
                    }
                    intersection = new Manifold(Body, other.Body, n, offsetX);
                    return(true);
                }
                else
                {
                    // Point toward B knowing that n points from A to B
                    if (distance.y < Fix32.Zero)
                    {
                        n = new Vector2F(0, -1);
                    }
                    else
                    {
                        n = new Vector2F(0, 1);
                    }
                    intersection = new Manifold(Body, other.Body, n, offsetY);
                    return(true);
                }
            }
        }
        return(false);
    }