3

参考我目前正在构建的这个编程游戏。

多亏了这篇文章的答案,我现在能够找到矩形所有点的 xy 坐标(即使在旋转时),并且墙壁碰撞检测现在几乎可以完美运行。

现在我需要用机器人自己实现碰撞检测(因为很明显,Arena 中会有不止一个机器人)。

Square-Square Collision Detection (Non-rotated) 在这种情况下无效,因为机器人会以一定角度转动(就像我在这里描述的那样)。

那么在 WPF 中实现这种形式的旋转矩形碰撞检测的最佳方法是什么?

我想肯定涉及到一些数学,但通常事实证明 WPF 中有一些函数可以为您“计算”这些数学(就像在这种情况下一样

4

2 回答 2

9

解决方案

通过使用我发布的作为上一个问题的解决方案的方法和称为IntersectsWith(from Rect) 的 WPF 方法,我能够解决旋转矩形碰撞检测的问题,如下所示:

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;
}
于 2009-02-28T11:37:08.613 回答
0

我会检查每条线是否有碰撞(所以你最多可以进行 4*4 线碰撞检查,如果两条线发生碰撞,机器人也会这样做,你可以停下来),尽管我确信有更好/更快的方法去做这个。如果矩形可以有不同的大小,您还应该检查较小的是否在另一个内部。

如果您首先检查矩形的旋转 x/y-min/max-value(或者您甚至可以计算机器人周围的两个圆圈并检查它们,这甚至更快),性能可能会略有提高,所以您没有检查线条是否彼此远离。

于 2009-02-28T10:05:33.733 回答