【问题标题】:WPF: Collision Detection with Rotated SquaresWPF:使用旋转方块进行碰撞检测
【发布时间】:2009-02-28 08:57:42
【问题描述】:

参考this programming game我目前正在建设中。

感谢this post 的回答,我现在能够找到矩形所有点的 x-y 坐标(即使旋转时也是如此),并且墙碰撞检测现在几乎可以完美运行。

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

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

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

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

【问题讨论】:

    标签: wpf math rotation collision-detection


    【解决方案1】:

    解决方案

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

    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;
    }
    

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 2022-08-19
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多