如何检查旋转对象平移点碰撞

本文关键字:对象 碰撞 旋转 何检查 检查 | 更新日期: 2023-09-27 18:15:09

我在WindowsForm上有两个矩形,我想检查它们是否碰撞。对于简单的非旋转碰撞,它看起来像这样:

Point newLocation; // upper-left corner of the object to check its collision
Size objectSize; // the object size
bool collision = false;
foreach (Object otherObject in otherObjects)
{
    if (newLocation.X >= otherObject.location.X && newLocation.X <= otherObject.location.X + otherObject.size.width)
        if (newLocation.Y >= otherObject.location.Y && newLocation.Y <= otherObject.location.Y + otherObject.size.height)
        {
            collision = true;
            break;
        }
}

但是现在我用

旋转两个对象
Matrix matrix = new Matrix();
matrix.RotateAt(angle, newLocation);
graphics.Transform = matrix;

我如何检查旋转矩阵的碰撞?我能得到平移后的X, Y坐标吗?

如何检查旋转对象平移点碰撞

我有一些代码将点从标准坐标系转移到特定坐标系(但在您的情况下,Y在屏幕上向下增加,因此进行了一些调整并注释)。

在这里,双精度[]表示一个点,其中索引0为X坐标,索引1为Y坐标。注意,新坐标系的角度是逆时针测量的,单位是弧度。(乘以Pi/180将度转换为弧度)。

    /// <summary>
    /// Implemented - Returns the point coordinates related to a new coordinate system
    /// Does not change original point
    /// </summary>
    /// <param name="Point">Point to be returned in new coordinate system</param>
    /// <param name="NewSystemCouterClockRotation">CounterClokWise Angle of rotation of the new coordinate system compared to the current, measured in radians</param>
    /// <param name="NewSystemOrigin">Location of the new origin point in the current coordinate system</param>
    /// <returns></returns>
    public double[] ChangeCoordinateSystem(double[] Point, double NewSystemCouterClockRotation, double[] NewSystemOrigin)
    {
        //first adjust: fix that winform downwards increasing Y before applying the method
        Point[1] = -Point[1];
        NewSystemOrigin[1] = -NewSystemOrigin[1]
        //end of first adjust

        //original method
        double[] Displacement = new double[2] { Point[0] - NewSystemOrigin[0], Point[1] - NewSystemOrigin[1] };

        double[] Result = new double[2]
        {
            + Displacement[0] * Math.Cos(NewSystemCouterClockRotation) + Displacement[1] * Math.Sin(NewSystemCouterClockRotation), 
            - Displacement[0] * Math.Sin(NewSystemCouterClockRotation) + Displacement[1] * Math.Cos(NewSystemCouterClockRotation) 
        }; 
        //second adjust: reset Y of the result
        Result[1] = - Result[1];
        return Result;
    }

但是,如果你的两个对象有不同的角度,你应该小心,最好的方法是检查第一个矩形的all four corners of the first是否不在另一个对象内,并且the other object four corners是否也不在第一个矩形内。

可以在这里找到一些算法来确定一个点是否在多边形内:多边形中的点