1

I've been trying to write some collision detection code in C, below is the function i have at the moment, its called every frame however for some reason when the 2 sprites overlap the collision doesn't work

short int Collision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2)
{
    int left1, left2;
    int right1, right2;
    int top1, top2;
    int bottom1, bottom2;

    left1 = x1;
    left2 = x2;
    right1 = x1 + w1;
    right2 = x2 + w2;
    top1 = y1;
    top2 = y2;
    bottom1 = y1 + h1;
    bottom2 = y2 + h2;

    if ((bottom1 < top2)||(top1 > bottom2)||(right1 < left2)||(left1 > right2)) 
    {
        return(1);
    }

    else
    {
        return(0);
    }

    };

    if (Collision ==1)
    {
    //code for collision here
    }

Any pointers in the right direction would be greatly appreciated

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
user1902320
  • 35
  • 1
  • 2

2 Answers2

1

I know, there is a correct single condition with 32 tags and 16 operators, but it's impossible to read and easy to mess up. My advice is: write more but simpler conditions.

bool collision = false;
do {
  if (top1 > bottom2) break;  // 1 is under 2
  if (top2 > bottom1) break;  // 1 is beyond 2
  if (left1 > right2) break;  // 1 is right to 2
  if (left2 > right1) break;  // 1 is left to 2
  // I think we listed all the non-collide cases  
  collision = true;
} while (false);

If "touch" counts as non-collision, >= should used instead > -s. A good compiler should produce same code from this and from a long complex condition.

ern0
  • 3,074
  • 25
  • 40
  • Yep, only to make *break* work. – ern0 Dec 13 '12 at 22:07
  • tried this set up and still no effect when the sprites collide – user1902320 Dec 13 '12 at 22:16
  • Don't you have the typical bug mixing x/y w/h? Some coordinate systems use y for vertical, others for horizontal, and it's easy to miss. – ern0 Dec 13 '12 at 22:24
  • im fairly sure the co-ordinate system is correct, but either way this would just mean that the collision occurs in the wrong place rather than not at all – user1902320 Dec 13 '12 at 22:33
  • ok I've made some progress, after correcting some things suggested on here (thnx btw). I foundthat there was an issue with the function returning values to be used in the rest of the program, im not entirely sure why yet, but its a start. – user1902320 Dec 13 '12 at 23:00
  • ... You know C has goto for that, right? No need to hurt an innocent `do` loop :p – Quentin Nov 08 '17 at 14:13
0

Remember that (0,0) vertex is the top left and not the bottom left. Hence, y(vertical axis) increases downwards and x(horizontal axis) increases rightwards.

So, bottom1 < top2 means there if no collision and similar are your other conditions

Robin Chander
  • 7,225
  • 3
  • 28
  • 42