gamer
gamer

Reputation: 11

How do I detect a collision between two rectangles

I have a player with destination

srcRect.w = 100;
srcRect.h = 64;
destReact.x = 1535 / 2;
destReact.y = 400;  
destReact.w = srcRect.w * 2;
destReact.h = srcRect.h * 2;

and a rock of dest and src

srcRect1.w = 64;
srcRect1.h = 64;
srcRect1.x = 0;
srcRect1.y = 0;

destReact1.x = 250;
destReact1.y = ypos;
destReact1.w = srcRect1.w * 2;
destReact1.h = srcRect1.h * 2;

I want to detect when they collide

Upvotes: 1

Views: 448

Answers (1)

The player and the rock, both have a bounding rect. There is a collision, if the rectangles intersect.

Since you're using SDL2, have a look at the function SDL_IntersectRect:

SDL_bool SDL_IntersectRect(const SDL_Rect * A,
                           const SDL_Rect * B,
                           SDL_Rect * result);

Calculate the intersection of two rectangles.

Return Value

Returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise.

Upvotes: 4

Related Questions