Simple tile collisions

Monkey Forums/Monkey Programming/Simple tile collisions

elite_dtn(Posted March) [#1]
Just wondering what the easiest way of having tile collisions for my game is, i have a level class i think the collision code will go in here but not really sure how to address this.


Soap(Posted March) [#2]
There are many ways to do it. Study existing examples to understand the different ways and find best way to do it for your project.

https://github.com/swoolcock/diddy/blob/develop/src/diddy/tile/renderer.monkey


elite_dtn(Posted March) [#3]
Are there any simple ones that dont use any other frame works just the simple Monkey X?


Gerry Quinn(Posted March) [#4]
A lot depends on how fancy the collisions need to be. Will a circular or rectangular hit-box be enough? In this case it's easy to roll your own, assuming there aren't so many collisions that you need to use quad trees and such like.

If you want per-pixel collisions, it's a bit more complicated (still doable of course). But you can start with a rectangular hit-box and implement per-pixel later as a second, more accurate stage.


elite_dtn(Posted March) [#5]
A rectangular hit box would be fine for the purpose, it is a platform game so when the player collides with a platform tile it holds the character. I also have a lava tile so it will need to end the level if a collision occurs.


Gerry Quinn(Posted March) [#6]
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.