Advertisement
Guest User

Sprite Collision Test Function

a guest
Apr 28th, 2011
703
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. //collision test function. Returns true if sprites are touching.
  2. bool collision(sprite_t sprite_1, sprite_t sprite_2){
  3.   //Let's examine the x axis first:
  4.   //If the leftmost or rightmost point of the first sprite lies somewhere inside the second, continue.
  5.   if( (sprite_1.x >= sprite_2.x && sprite_1.x <= (sprite_2.x + sprite_2.w)) ||
  6.       ((sprite_1.x + sprite_1.w) >= sprite_2.x && (sprite_1.x + sprite_1.w) <= (sprite_2.x + sprite_2.w)) ){
  7.     //Now we look at the y axis:
  8.     if( (sprite_1.y >= sprite_2.y && sprite_1.y <= (sprite_2.y + sprite_2.h)) ||
  9.         ((sprite_1.y + sprite_1.h) >= sprite_2.y && (sprite_1.y + sprite_1.h) <= (sprite_2.y + sprite_2.h)) ){
  10.       //The sprites appear to overlap.
  11.       return true;
  12.     }
  13.   }
  14.   //This algorithm will not detect collisions if sprite_2 is smaller than sprite_1.
  15.     //To solve this problem, we'll check again, using sprite_2 in place of sprite_1.
  16.     if( (sprite_2.x >= sprite_1.x && sprite_2.x <= (sprite_1.x + sprite_1.w)) ||
  17.       ((sprite_2.x + sprite_2.w) >= sprite_1.x && (sprite_2.x + sprite_2.w) <= (sprite_1.x + sprite_1.w)) ){
  18.     //Now we look at the y axis:
  19.     if( (sprite_2.y >= sprite_1.y && sprite_2.y <= (sprite_1.y + sprite_1.h)) ||
  20.         ((sprite_2.y + sprite_2.h) >= sprite_1.y && (sprite_2.y + sprite_2.h) <= (sprite_1.y + sprite_1.h)) ){
  21.       //The sprites appear to overlap.
  22.       return true;
  23.     }
  24.   }
  25.   //The sprites do not overlap:
  26.   return false;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement