Thursday, October 17, 2013

Tiled / Cocos2D: Using Objects


  1. Go to Tiled, create an object layer
  2. On the object layer, add objects by using the drawing shapes
  3. If you are using rectangular shapes to represent tiles, you can open the object properties sub-menu after selecting the object and adjust the position and size to fit perfectly the tile
  4. Load the map in Cocos2D and read it with the following code (Example is C++ using Cocos2D-X):

   CCTMXObjectGroup* objectGroup = map->objectGroupNamed(objGroupName);
   CCArray* objects = objectGroup->getObjects();
   
   CCDictionary* objectAsDict;
   CCObject* obj;
   CCARRAY_FOREACH(objects, obj)
   {
       objectAsDict = (CCDictionary*)obj;
       if(!objectAsDict)
       {
           break;
       }
       const char* key = "x";
       int x = ((CCString*)objectAsDict->objectForKey(key))->intValue();
       key = "y";
       int y = ((CCString*)objectAsDict->objectForKey(key))->intValue();
       key = "width";
       int width = ((CCString*)objectAsDict->objectForKey(key))->intValue();
       key = "height";
       int height = ((CCString*)objectAsDict->objectForKey(key))->intValue();


       // figure out which tiles are covered the rectangle here
   }

Note that the coordinates for the rectangle are based on the coordinate system of an ortho tile map (with origin at bottom left). If you are using an iso tile map in Cocos2D, the origin is at the top of the diamond. You'll have to do the necessary conversion.

No comments:

Post a Comment