|
Collision Detection
Sometimes, when writing your own game loop in Verge, you will need to be able to see if one object is touching or inside another object. For example, hitting an enemy with bullets in a platformer, or running over powerups in a racing game, among others. Collision detection in a game may seem tough, but there is an easy method. All you have to ask yourself, is what does it really mean when an object is colliding with another?
When 2 objects colide, in programming terms, then they are overlapping each other at some point.
The colored areas are where the two rectangles intersect each other. By now, you should be getting a general idea of the algorithm. You might also be thinking, "shut up and get to the bloody point and show me the code!". Allright, I will. ~_^
#define true 1
#define false 0
int CheckForCollision(int X1, int Y1, int W1, int H1, int X2, int Y2, int W2, int H2) // x/y locations of the two objects, and their widths and heights.
{
if (X1+W1 < X2) return false; // object1 is to the left of object2.
if (X1 > X2+W2) return false; // object1 is to the right of object2.
if (Y1+H1 < Y2) return false; // object1 is above object2.
if (Y1 > Y2+H2) return false; // object1 is below object2.
return true; //if it gets here, they overlap.
}
Simple, no? Much faster than checking each individual pixel. Hopefully, someone will find this useful.
|