1

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
  • 1
    Do you want it to return an int? If so, what value would you like represented? Commented Aug 21, 2010 at 6:07

3 Answers 3

3

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) {
Sign up to request clarification or add additional context in comments.

Comments

2

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

12 Comments

@NeoHaxxor - simple, yes, but do you understand why it works?
Any reason for the downvote? Please leave a comment when downvoting.
why you want to change the return type of function , you can use something like this int result = (dxdy)+(dydy)< radii * radii ? 1:0 and retrun result ;
@saurab, because when a function has to determine whether two points collide it should return a boolean value. It expresses much more clearly its intent to the consumer.
@saurabh, the code's already broken and there cannot be any consumers of this method simply because this method doesn't even compile. So I really don't understand your point.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.