[英]How to check for rotated objects translated points collisions?
我在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增加了屏幕上的顏色,因此進行了一些調整和注釋)。
在這里,double []代表一個點,其中索引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
一個矩形中第一個矩形的all four corners of the first
是否不在另一個對象內, the other object four corners
是否不在the other object four corners
內里面也一樣。
可以在此處找到一些算法來找出點是否在多邊形內: 點在多邊形中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.