不同的物体相撞

时间:2013-04-14 11:30:03

标签: c++ c geometry

我只想检查两个物体是否发生碰撞,在这种情况下它是一个圆圈,第二个是方形。我正在使用的代码工作得很好,但它只检查方块的正确向下/ buttom 侧是否发生碰撞,请帮我纠正它以便我可以能够检查所有方面的碰撞。

enter image description here

问题是我只想检查方块的所有边是否与圆相撞,但它只检查下面的功能的两侧:

 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;
     }

显示错误的图片:

当圆圈向左移动但仍未触及方块时:

enter image description here

现在当它触及方块时,它会按原样返回true:

enter image description here

当圆圈偏向右边但仍未触及方格时,它返回false:

enter image description here

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

enter image description here

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

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试这个

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时,函数将退出它的范围.. < / p>