WPF: collision detection with turned squares

advertisements

With reference to this programming game I am currently building.

Thanks to the answers from this post, I am now able to find the x-y coordinates of all the points of the rectangles (even when rotated), and Collision-Detection with Walls is almost working perfectly now.

Now I need to implement collision detection with the bots themselves (cause obviously, there will be more than one bot in the Arena).

Square-Square Collision Detection (Non-rotated) is not valid in this case because the bots will be turned at an angle (just like I described here).

So what is the best way to implement this form of Rotated Rectangles Collision Detection in WPF?

I guess there must be some math involved, but usually it turns out that there are functions in WPF that "calculate" these maths for you (just like in this case)


Solution

By using the method I posted as a solution to this previous question and a WPF method called IntersectsWith (from Rect), I was able to solve this issue of rotated rectangles collision detection like so:

public Rect GetBounds(FrameworkElement of, FrameworkElement from)
{
        // Might throw an exception if of and from are not in the same visual tree
        GeneralTransform transform = of.TransformToVisual(from);

        return transform.TransformBounds(new Rect(0, 0, of.ActualWidth, of.ActualHeight));
}

Vehicle IsBotCollided(IEnumerable<Vehicle> blist)
{
    //currentBounds is of type Rect, which contains the 4 points of the rectangle (even when rotated)
    var currentBounds = GetBounds(BotBody, BattleArena);

    //Then I check if the current bounds intersect with each of the other Bots` bounds that are also in the Arena
    foreach (Vehicle vehicle in blist)
    {
        if(GetBounds(vehicle.BotBody, BattleArena).IntersectsWith(currentBounds))
        {
            return vehicle;
        }
    }
    return null;
}