Cannot implicitly convert 'bool' to 'int' - collision detection

落花浮王杯 提交于 2019-12-24 08:38:07

问题


I am trying to make a simple collision detection class for a soccer game. Here is the code:

int Collision(int x1, int y1, int radius1, int x2, int y2, int radius2)  
{  
    int dx = x2 - x1;  
    int dy = y2 - y1;  
    int radii = radius1 + radius2;  
    if ((dx*dy)+(dy*dy)< radii * radii)  
    {  
        return true;  
    }  
    else  
    {  
        return false;  
    }  
}  

The problem is with the code returning true or false. Visual Studio says it cannot implicitly convert bool to int, and I understand that, but how can I fix it? Thanks for any help.


回答1:


Define your function like this:

bool Collision(int x1, int y1, int radius1, int x2, int y2, int radius2)

Now you can return true or false. If you keep int then you need to return an integer value such as 0 and 1 but this doesn't express the function intent.

You could also shorten your code a bit:

bool Collision(int x1, int y1, int radius1, int x2, int y2, int radius2)  
{  
    int dx = x2 - x1;  
    int dy = y2 - y1;  
    int radii = radius1 + radius2;  
    return ((dx * dy) + (dy * dy) < radii * radii);
}



回答2:


If you need to return a true/false variable, you should change your first line to this:

bool Collision(int x1, int y1, int radius1, int x2, int y2, int radius2) {



回答3:


Don't forget to fix your algorithm. ((dx***dy**)+(dy*dy)< radii * radii) should be: ((dx***dx**)+(dy*dy)< radii * radii)

Just when you think: Whew! I fixed that int/bool thing,, you get a bunch of false positives.



来源:https://stackoverflow.com/questions/3536556/cannot-implicitly-convert-bool-to-int-collision-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!