Your logic with regard to how to handle collisions will probably be more complex than the collisions themselves. For example, you may want to be able to jump up through tiles, but land when you fall onto them. And note that if your character is walking on a platform, he is NOT colliding with it. You have to determine whether he would collide if he fell a little bit, and not fall if so. For example, he might always fall a small distance at every update, and if he turns out to be intersecting a tile he goes up again the same distance. And if the tile was lava he dies.
Code for rectangle intersections could look like the following (your class might have an explicit rectangle object for a hitbox, or it might just have the same data as class fields):
The first line says, if the left of rectangle 1 is further right than the right of rectangle 2, there's no collision. The other three cover the three other sides of each rectangle. If you draw it on paper, you'll see that if none of the four conditions are true, then the rectangles must intersect.
Now if there are many platform tiles, you'll want to be efficient, and you might not have full rect data stored for each tile if they are all the same size. You might get tile rectangle data directly from the logical coordinates of the tile. And you don't want to be creating lots of objects each frame. You might start with the character position and find the nine nearest tiles and just test those. But those are implementation details - the math will be the same. It's all a matter of building things up step by step.
|