简体   繁体   English

二维旋转矩形包含点计算

[英]2D Rotated rectangle contains point calculation

My issue is that I've been trying to check if a rectangle that is rotated by a certain amount of degrees contain a point, but I wasn't able to calculate that after many attempts with the help of some code samples and examples that I've found online.我的问题是,我一直在尝试检查旋转了一定度数的矩形是否包含一个点,但是在一些代码示例和示例的帮助下,经过多次尝试,我无法计算出该点已经在网上找到了。

What I got is the rectangle (X, Y, Width, Height, Rotation) and the point (X, Y) and I've been trying to create a simple function that lets me instantly calculate that, which would be something something like this:我得到的是矩形(X,Y,宽度,高度,旋转)和点(X,Y),我一直在尝试创建一个简单的函数,让我立即计算它,这将是这样的:

public bool Contains(Rect Rectangle, float RectangleRotation, Point PointToCheck);

But as I mentioned, I wasn't able to do so, those mathematical calculations that include some formulas I found online are way too much for me to understand.但正如我所提到的,我无法这样做,那些包含我在网上找到的一些公式的数学计算对我来说太难理解了。

Could someone help me with calculating this?有人可以帮我计算一下吗? If you could provide the calculation in C# code form (not formulas) then that would be great!如果您能以 C# 代码形式(不是公式)提供计算,那就太好了! Thanks.谢谢。

PS: Using the 2D Physics Engine that is available in Unity3D is not a option, my rectangle is not associated with a gameobject that I could attach a 2D collision component to, I need to do this mathematically without the involvement of gameobjects or components. PS:使用 Unity3D 中可用的 2D 物理引擎不是一种选择,我的矩形与我可以附加 2D 碰撞组件的游戏对象无关,我需要在不涉及游戏对象或组件的情况下以数学方式执行此操作。

Edit: I forgot to mention, the rectangle is being rotated by the middle of the rectangle (center/origin).编辑:我忘了提到,矩形正在由矩形的中间(中心/原点)旋转。

Rather than checking if the point is in a rotated rectangle, just apply the opposite of the rotation to the point and check if the point is in a normal rectangle.与其检查点是否在旋转的矩形中,只需将旋转的相反方向应用于该点并检查该点是否在正常矩形中。 In other words, change your perspective by rotating everything by -RectangleRotation , so that the rectangle does not appear rotated at all.换句话说,通过-RectangleRotation旋转所有内容来改变你的视角,这样矩形就不会出现旋转。

public bool Contains(Rect rect, float rectAngle, Point point)
{
    // rotate around rectangle center by -rectAngle
    var s = Math.Sin(-rectAngle);
    var c = Math.Cos(-rectAngle);

    // set origin to rect center
    var newPoint = point - rect.center;
    // rotate
    newPoint = new Point(newPoint.x * c - newPoint.y * s, newPoint.x * s + newPoint.y * c);
    // put origin back
    newPoint = newPoint + rect.center;

    // check if our transformed point is in the rectangle, which is no longer
    // rotated relative to the point

    return newPoint.x >= rect.xMin && newPoint.x <= rect.xMax && newPoint.y >= rect.yMin && newPoint.y <= rect.yMax;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM