Cocos2D-X Platformer tutorial Part 6 – Collision

Collision detection with tilemaps in Cocos2D-x can be a pain (will explain shortly), but I managed to find a clean solution for it.

In the first part when we set the initial position of the player (10,2), we assumed the origin is at (0,0).
This is actually fine, but when I try to get a tile using same coordinate(10,2) from the layer named “walls” in the tmxmap will return null.
Why? This is because the origin in the tmxmap begins at upper-left corner, so according to tmxmap’s height our starting point (10,2) is actually (10,17). Here see the highlighted square and notice the coordinate at bottom left.


To get around this we have to reverse the position when we use tmx layers methods and subtract -1 because index begins at 0.

New stuff

  • positionToTileCoordinate – convert screen position to tile coordinate
  • getCollisionTiles(point, x, y) – get tiles around sprite, if you enter -1 for x and y, you will get all 9 sprites (I mighty change this a bit in upcoming parts)

Recent Posts