我在屏幕上绘制了两个正方形,如何检测两个对象边缘的碰撞?

现在,我可以比较X和Y来检查碰撞,但这只是两个物体在完全相同的X和Y位置上正好穿过彼此。 由于缺乏更好的术语,我需要更准确地检查碰撞,检查撇渣。 我有X,Y,X和Y标度的变量以及X和Y的速度。非常感谢任何帮助:D

编辑:广场!

如果您的方块不能旋转,则很容易:比如说, double r是每条边的长度, Point p1是一个方格的中心, p2是另一个方格的中心。 然后:

 if (Math.abs(p1.x - p2.x) < r && Math.abs(p1.y - p2.y) < r) { // Collision } 

更复杂的情况是如果一个正方形可能被旋转。 在这种情况下:将对象的每个边缘视为几何线(如果知道角的坐标,则可以轻松计算每条线的等式)。

接下来,找到每两行的会合点(每个行从一个正方形到另一个正方形),并测试该点是否在其中一个正方形内。 如果其中一个比较返回true,则发生碰撞。

如果矩形可以旋转,您只需更改坐标系,使其中一个轴对齐,然后检查另一个顶点的每个顶点,看它是否(顶点)在轴对齐内长方形。 您可以通过围绕同一点旋转两个矩形的所有顶点来更改坐标系。 该旋转的角度应该是旋转矩形的旋转角度的否定。 例如,如果一个矩形倾斜13°,您可以将两个矩形的顶点绕同一点旋转-13°。

Elist是/是一个巨大的帮助! 然而,我发现这在我的第一个广场周围创造了一个大方块,并搞砸了碰撞。 这是我基于Elistpost的实现。

 public boolean colliding(Square os) { // the lesser value is the distance of the square's width and that of the lenght of the // other square return Math.abs(center.x - os.center.x) < width / 2 + os.width / 2 && Math.abs(center.y - os.center.y) < height / 2 + os.width / 2; } 

对Elist的所有应有的尊重,如果没有他们的post我就不会得出这个结论。

对那些感兴趣的人的额外帮助将是一个可以阻止传入方块的处理程序,以及一个根据其他方块速度反映它的方法。

 // stops the square from intersecting public void push_collided_basic(Square os, float refelct_amnt) { if(os.center.x < center.x) os.center.x -= refelct_amnt; else if(os.center.x > center.x) os.center.x += refelct_amnt; if(os.center.y < center.y) os.center.y -= refelct_amnt; else if(os.center.y > center.y) os.center.y += refelct_amnt; } // and now one that reflects the ball -> untested!!! public void push_collided_velocity(Square os) { // flip the velocitys directions for x if(os.center.x < center.x || os.center.x > center.x) os.vel_x *= -1; // flip the velocity direction for y if(os.center.y < center.y || os.center.y > center.y) os.vel_y *= -1; // update the coordiantes os.center.x += vel_x; os.center.y += vel_y; }