I'm teaching myself game programming using SDL. This means that I'm relearning C (the "get my Java learn-on" thread is currently suspended). C is just barely acceptable. The executables are blickin' fast but the development speed (even for easy things) is second only to assembler. Of course, stupid bugs don't shorten development time. Even when printf statements and gdb, it took me an hour to track done the one below. The code attempts to determine whether one segment (described by the Sprite structure) crosses another. The way I chose to solve this is to iterate through the set of points for both segments. This isn't the fastest method, but it is commensurate to my level of math. :-)
Anyway here's the code. The problem is that the code loops forever. Can you see why?
int Collision (Sprite * a, Sprite * b) { int ax, ay, bx, by; int collision = 0; for (ax = a->p.x; ax < a->length; ax++) { ay = (int) ceil(a->slope * ax) + a->p.y; for (bx = b->p.x; bx < b->length; by++) { by = (int) ceil(b->slope * bx) + b->p.y; if (ax == bx && ay == by) { collision = 1; return(collision); } } } return(collision); }
Hint: This bug could just have easily happened in Perl. Man, I'm just stupid.
Update: Sweet Jesus, there's a semantic bug too! If you can see why this function won't detect collisions that occur beyond the length of Sprite a, give yourself a quarter. :-)
My C is also slightly rusty, but I'm guessing that, at some point, you really ought to increment bx
. I'd do it within the inner loop, too.