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.

map

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)


  • j

    is the next step coming soon? no need to rush, just wondering

    • metin

      maybe on the weekend 🙂

  • pablo

    to the point and clear. please finish the gravity section Asap. would be very helpful to me

  • Andy

    Support for Vector is not available in Cocos2d-x v3.9. It throws up an error “Invalid type for cocos2d::Vector”. Any idea on how to fix it?

    • Andy

      I meant Vector

      • Andy

        Sorry, the the HTML tag filtering eats up Rect

    • Andy

      Managed to fix it. I didn’t notice that you were utilising the c++ vector and not the cocos2d Vector.

      • metin

        Yes, I always try to use what’s already available.

Recent Posts

Recent Comments

Categories