旋转矩形的碰撞检测 [英] Collision detection with rotated rectangle

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

问题描述

好的我需要检查鼠标是否单击了一个矩形,显然当矩形没有旋转时这是微不足道的,但是当它变得越来越难时。



阅读了不少帖子后我相信你必须反转点和矩形的旋转(我已经将矩形移动到原点,所以它具有相同的旋转中心矩阵),然后简单地做一个正常的边界检查。



这是我到目前为止所得到的,但它不起作用:

Ok I need to check if a mouse click has clicked on a rectangle, obviously this is trivial when the rectangle hasn't been rotated, but when it has it gets harder.

After reading quite a few posts I believe you have to reverse the rotation of the point and rectangle (I have moved rectangle to origin so it has the same rotation centre as the matrix), then simply do a normal bounds check.

This is what I have got so far, however it doesn't work:

bool isClicked()
{
    Vector2 origLoc = Location;
    Matrix rotationMatrix = Matrix.CreateRotationZ(-Rotation);
    Location = new Vector2(0 - (Texture.Width / 2), 0 - (Texture.Height / 2));
    Vector2 rotatedPoint = new Vector2(Game1.mouseState.X, Game1.mouseState.Y);
    rotatedPoint = Vector2.Transform(rotatedPoint, rotationMatrix);

    if (Game1.mouseState.LeftButton == ButtonState.Pressed &&
        rotatedPoint.X > Location.X &&
        rotatedPoint.X < Location.X + Texture.Width &&
        rotatedPoint.Y > Location.Y &&
        rotatedPoint.Y < Location.Y + Texture.Height)
    {
        Location = origLoc;
        return true;
    }
    Location = origLoc;
    return false;
}

推荐答案

矩形有四个点。通过将点的位置乘以旋转矩阵,您必须在旋转后获得这四个点的位置。然后从形成矩形墙的每两个点创建一个2D平面。现在您可以检查鼠标位置是在平面前面还是在平面后面。如果它在所有平面后面,则意味着鼠标与矩形相撞。希望这可以帮助。我只是用非常简短的话给你解决方案。



如果你需要代码如何从两点创建飞机以及如何检查一个点是否在后面/前面平面。你可以很容易地在谷歌上找到它。
A rectangle has four Points. You have to get the position of those four points after rotation by multiplying the position of point with rotation matrix. Then create a 2D plane from every two points which make a wall of the rectangle. Now you can check whether the mouse position is in front of plane or behind the plane. If it is behind the all the planes then it means mouse has collided with the rectangle. Hope this helps. I just gave you solution in very short words.

If you need code how to create plane from two points and how to check if a point is behind/front of a plane. You can find it on google very easily.


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

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