我只想检查两个物体是否发生碰撞,在本例中是圆形,第二个是方形。我使用的代码完美运行,但它只检查正方形的right 和down/buttom 侧是否发生碰撞,请帮助我更正它以便我可以能够检查所有侧面的碰撞。
问题是如果正方形与圆碰撞,我只想检查它的所有边,但它只检查两个边,下面有函数:
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 <= squareX + width
&& circleY >= 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:
现在当它接触正方形时它仍然返回 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 时,函数将从它的范围退出......
关于c++ - 不同物体碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15998565/