As per the requirements, I assume you need bounding box collision detection? Per-pixel is harder, but not that hard if the sprites don't transform.
would really appreciate "back to basics" tips and advice |
Alright, so we're looking for the answer to "when does a sprite touch another sprite"? For the purposes of this, a "sprite" is just an image (which may have transparency). The image has a boundary, which we call the bounding box.
Let's say we have a sprite whose bottom-left corner is at (5,6), with a width of 100 and a height of 200 (I assume a bottom-left origin though this may be different for your application). We would say that the width of the bounding box spans from x=5 to x=105 (let's call this set
Spanx) and the height spans from y=6 to y=206 (let's call this set
Spany). So far, so good.
Now, let's say we have a point (x,y). How do we determine if the point is within the bounding box above? (spoiler ahead) It is sufficient to check that x lies within
Spanx and y lies within
Spany.
1 2 3 4
|
int checkX = 100;
int checkY = 210;
bool pointInBoundingBox = (checkX >= 5) && (checkX <= 105) && (checkY >= 6) && (checkY <= 206);
//pointInBoundingBox == false because checkY > 206
|
The following is wrong (see my next post)
This simple observation is all we need to answer the question "does sprite A collide with/touch sprite B". (spoiler ahead) To answer it we simply need to check the four corners of one of the sprites. If at least one of the corners is within the other bounding box (see above) then the sprites collide!
Now, judging by your requirements, for each frame, you only need to check if the player touches/collides with any of the enemies. If there are N enemies, then the brute force "check the player's bounding box with all the enemies' bounding boxes" is O(N) (linear time), so going that approach won't hurt rendering time very much (unless there are many many enemies on screen).
Hopefully the above will satisfy the requirements for your assignment. A more scalable approach would be to use a "broad phase" collision detection step which would rapidly determine pairs of sprites that
may collide followed by the test above for each pair. There are many ways to partition the scene for the "broad phase" step such as using a simple grid of cells or a quad tree. I doubt your professor would require that, but if they do I would be happy to explain further.