Search code examples
javajava-2d

What is the logic behind collision detection in 2d games?


I want to create a 2D game with a tile based map. My main problem is collision. If there is a tree in my way, how will I make my sprite not move through the tree?


Solution

  • Pseudo-code:

    some_event() {
        if (bullet.x == monster.x && bullet.y == monster.y) {
            collision_occurs();
        }
    }
    

    Of course the semantics such as which event will be fired and whether or not an event handler makes more sense (i.e.: collision_occurs() when the x and y coordinates meet, rather than if they meet while some_event() is fired) depend on the game.

    If you were to analyze this more you would notice that the bullet and monster aren't 1 pixel each, so it would look more like:

    // While approaching from the left
    if ((bullet.x + (bullet.radius)) >= (monster.x + (monster.radius)))
    

    These fine details come after. Essentially you have moving objects and these objects share coordinates. When these coordinates, as properties of their representational objects, are near enough, a "collision" occurs and some methodology follows.