c++ - 不同物体碰撞

标签 c++ c geometry

我只想检查两个物体是否发生碰撞,在本例中是圆形,第二个是方形。我使用的代码完美运行,但它只检查正方形的rightdown/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

现在当它接触正方形时它仍然返回 false,这是错误的:

enter image description here

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

enter image description here

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

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 (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/

相关文章:

c++ - 是否可以从可变参数模板调用多个基类构造函数?

C代码到快速转换

c - 使用 MPI 同时发送和接收

iphone - 查找 map 上的线和点之间的距离

javascript - Three.js 敌人向玩家移动

C++:将结构的类型更改为子类型

c++ - 关键字 "const"是如何工作的?

c++ - 如何显示集合中的某个项目 C++

c - 将大量 xml 文件转换为文本时出现段错误

algorithm - 我如何知道多边形的内部是位于顶点的右侧还是左侧?