WPF:旋转正方形的碰撞检测 [英] WPF: Collision Detection with Rotated Squares

查看:147
本文介绍了WPF:旋转正方形的碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考此我正在开发的编程游戏.

感谢这篇文章的答案,我现在能够找到矩形所有点的xy坐标(即使旋转时),并且与墙壁碰撞检测"现在几乎可以正常工作.

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).

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

我猜必须涉及一些数学,但是通常事实证明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)

推荐答案

解决方案

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

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

这篇关于WPF:旋转正方形的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆