不同的物体相撞

我只想检查两个物体是否发生碰撞,在这种情况下它是一个圆圈而第二个是方形。 我正在使用的代码完美无缺,但它只检查方块的右侧/侧面是否发生碰撞,请帮助我纠正它,这样我就可以检查所有侧面的碰撞。

在此处输入图像描述

问题是我只想检查广场的所有边是否与圆相撞,但它只检查两侧的function如下:

bool Collision(int circleX, int circleY, int radius, int squareX, int squareY, int width, int height) { double distance = 0; //get circle of square double center_square_x = (double)(squareX + squareX + width)/2; double center_square_y = (double)(squareY + squareY + height)/2; //check for whether circle fully located inside square if (circleX >= squareX && circleX = squareY && circleY <= squareY + height) return true; distance = pow (circleX - center_square_x,2.0) + pow(circleY - center_square_y,2.0); if( distance <= pow(radius, 2.0)) return true; else return false; } 

显示错误的图片:

当圆圈靠左时仍然没有碰到方块:

在此处输入图像描述

现在当它触及方块时,它会按照需要返回true:

在此处输入图像描述

当圆圈靠右时仍然没有碰到方格时它会返回false:

在此处输入图像描述

现在当它碰到方块时它仍然是假的,这是错误的:

在此处输入图像描述

当圆圈上升到正方形的触点并触摸时,它返回true,这是正确的:

在此处输入图像描述

但是当圆圈下降到正方形的顶部并触摸时,它返回false,这是错误的:

在此处输入图像描述

试试这个

 bool Collision(int circleX, int circleY, int radius, int squareX, int squareY, int width, int height) { double distance = 0; //get circle of square (the center of the rectangle or square is // (squareX + width)/2 and (squareY+height)/2 double center_square_x = (double)(squareX + width)/2; double center_square_y = (double)(squareY + height)/2; // check for each segment the circle position // check if the circle is between the bottom and upper square segments if (circleY >= squareY && circleY <= squareY + height) // check for left segment if (circleX >= squareX && circleX < centerX ) return true; // check for right segment else if (circleX <= squareX+width && circleX > centerX) return true; // check if the circle is between left and right square segments else if (circleX >= squareX && circleX <= squareX + width) // check for upper segment if (circleY >= squareY && circleY < centerY) return true; // check for bottom segment else if (circleY <= squareY + height && circleY > centerY) return true; 

我不知道你想通过距离计算实现什么,但它不会到达那里..因为当你在检查碰撞后返回true时,函数将退出它的范围。