• Create Account

# 0Circle0

Member Since 31 Jul 2011
Offline Last Active Sep 27 2014 04:32 PM

### #4846574How to check for collision between objects from 2 classes

Posted by on 09 August 2011 - 01:39 AM

Mine is optimized for objects of any size to be compared to other objects of any size where yours only checks if the 2nd object is smaller or equal to the 1st object. For your game it may work, but not every game. Mine however works for any as it check every single possible collision no matter the size of the object.

By the way, the code you linked only changes the direction of the ball, it isn't the collision detection code

```bool check_collision(SDL_Rect A, SDL_Rect B)
{
//Sides of rect
int leftA, leftB;
int rightA, rightB;

//Sides of rect A
leftA = A.x;
rightA = A.x + A.w;

//Sides of rect B
leftB = B.x;
rightB = B.x + B.w;

//If any of the sides from A are outside of B
if(rightA<=leftB)
{
return false;
}

if (rightB<=leftA)
{
return false;
}
//If none are outside
return true;
}
```

That is the collision code.Which should look like this.
```bool check_collision(SDL_Rect A, SDL_Rect B)
{
if (A.x + A.w <= B.x)
return false;
if (B.x + B.w <= A.x)
return false;
return true;
}
```
or even shorter:
```bool check_collision(SDL_Rect A, SDL_Rect B)
{
if (A.x + A.w <= B.x || B.x + B.w <= A.x)
return false; //Funny to return false on a collision detected
return true; //and true when there isn't one
}
```
```if (!check_collision(a, b)) //This says if check_collision == false, how you have it setup this would only
{ // execute if the statement were actually true as your function passes true when it is false.
...junk
}
```
Once it is that short, no reason to even waste time with a function call. Also:
No reason to add more variables when you do not need them.I just finished checking over your code a bit, and it seems you initialize a lot of variables that you don't need. So many that it isn't feasible to mention them all here. I'll assume you're new to programming, and if so you're headed in the right direction, but you're just doing some things the hard/long way as you can see from the above example.

### #4844857CLOSED:Sprite Generator I made

Posted by on 04 August 2011 - 10:12 PM

Updated the first post with latest version, and some outputs I randomly made.

### #4842830CLOSED:Sprite Generator I made

Posted by on 31 July 2011 - 08:18 AM

Closed

PARTNERS