yop
yop

Reputation: 141

C++ SDL collision between sprites

After 30 minutes Googling, all I could find is this: http://www.sdltutorials.com/sdl-collision

I thought the title was misleading, then I noticed it's just a nightmare of a way to detect collision between two sprites. All I want is to check whenever my player sprite touches something else (another sprite). How can I accomplish this?

I read there is a library called SDL_collision.h, but it's either in Pascal or empty.

Upvotes: 0

Views: 4313

Answers (1)

user1508519
user1508519

Reputation:

Chances are you'd use SDL_Rect for your bounding box. Where x and y are the positions of your sprite, and w and h are the width and height of your sprite. Then all you need to do is use SDL_HasIntersection.

Here is a simple example:

SDL_Surface *Srfc1, *Srfc2;
Srfc1= IMG_Load("foo.png");
Srfc2= Srfc1;
Srfc2->refcount++;

SDL_Rect box1, box2;
box1.x = box1.y = 0;
box2.x = box2.y = 100;
box1.w = box2.w = Srfc1->w;
box2.h = box2.h = Srfc1->h;

// ... somewhere in your event handling logic
if (SDL_HasIntersection(&box1, &box2))
{
    printf("Collision.");
}
// ...

SDL_FreeSurface(Srfc1);
SDL_FreeSurface(Srfc2);

Since you do not have SDL_HasIntersection, here's a quick little function that will suit your needs:

    bool IntersectRect(const SDL_Rect * r1, const SDL_Rect * r2)
    {
  return !(r2->x > (r1->x + r1->w) || 
           (r2->x + r2->w) < r1->x || 
           r2->y > (r1->y + r1->h) ||
           (r2->y + r2->h) < r1->y);
            );
    }

For reference the logic is:

  return !(r2.left > r1.right || 
           r2.right < r1.left || 
           r2.top > r1.bottom ||
           r2.bottom < r1.top);

Where 'right' and 'bottom' refer to 'x + width' and 'y + height' respectively. Use this to fix the function incase I made a typo.

Upvotes: 2

Related Questions