我试图判断两个矩形
是否发生碰撞。如果矩形不旋转,我没有问题,但当它们都旋转时,我的逻辑遇到一些问题。这是我目前正在使用的方法:
public static void car_on_ai_collision( AI ai, Entity e ){
//rotation of each rectangle in radians
double ai_rot = ai.getAIEntity().getRotation().y;
double car_rot = e.getRotation().y;
//stores the center point of the rectangles
Vector3f ai_loc = ai.getAIEntity().getLocation();
Vector3f car_loc = e.getLocation();
//here i am lining the square for my car up to a axis by making it have no rotation
ai_rot -= car_rot;
car_rot = 0;
//creating rectangles with the size of the car
Rectangle car = new Rectangle(175, 70);
Rectangle ai_rec = new Rectangle(175, 70);
car.translate((int) ((int) car_loc.x-87.5), (int) car_loc.z-35);
//rotation for rectangle
AffineTransform aiAT = new AffineTransform();
aiAT.translate((int) ai_loc.x - 87.5, (int) ai_loc.z-35);
aiAT.rotate( Math.toDegrees(ai_rot), ai_loc.x, ai_loc.z);
Area a = new Area(ai_rec);
a.transform(aiAT);
//testing for collision
if(a.getBounds2D().intersects(car)){
System.out.println("Collision!");
}
}
根据我的理解,碰撞检测似乎不太正确,其中一个轴需要对齐。我正在尝试对齐其中一个轴,然后测试与 AffineTransform 的碰撞,但我在网上看到一些有关旋转超过 90 度的内容会导致问题。我如何解决这个问题来测试两个旋转矩形之间的碰撞?任何帮助表示赞赏。
最佳答案
碰撞检测仅在两种情况下很简单:
- 圆圈之间
- 在对齐的矩形之间
SmashCode 解释了如何检测圆圈之间的碰撞。 对齐矩形就更简单了,只需比较矩形的最大和最小坐标是否重叠即可。
遗憾的是,您的情况不属于上述情况。这些矩形具有不同的坐标系,并且由于它们的旋转,其中一个矩形的边可能既不垂直也不平行于第二个矩形的轴,因此不能这样处理。
方法之一是使用边界框,就像您在此处所做的那样:
if(a.getBounds2D().intersects(car)){
System.out.println("Collision!");
}
调用 a.getBounds2D() 创建与坐标系对齐并覆盖整个形状的矩形。但边界框也会覆盖一些未被形状占用的空间。因此,检查对齐矩形和旋转矩形的边界框之间的碰撞既快速又简单,但可能会产生误报,如图所示 drawing of rectangles and bounding box of rotated one.
要全面、准确地检查碰撞,您需要使用一些更复杂的方法,例如 SAT使用将多边形转换(投影)到不同的轴上。事实上,您仅使用矩形意味着您只需要两个轴并且您已经知道它们的方向。
PS。使用边界框并没有错,这是检查两个图形是否不碰撞的简单方法(如果边界框不碰撞图形不能碰撞),您仍然可以使用它作为更快的预检查以消除明显的情况。关于java 两个旋转矩形之间的碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386632/