TMX Tilemaps & Box2D Fixtures

来源:互联网 发布:qq群机器人源码 编辑:程序博客网 时间:2024/05/22 14:36

TMX Tilemaps & Box2D Fixtures

There are many ways to make levels for a platformer. In this chapter we'll discuss how to create levels using tilemaps, then use Box2D to bring them to life.

A tilemap level uses an image file subdivided into a grid of tiles. The below screenshot shows a tileset named "Rock" with 16 x 16 pixel tiles.

A grid of tiles makes up a tileset

The tiles can be selected from the tileset and drawn to create a tilemap level.

A tilemap level

In the game Paralaxer, entirely gray tilesets are used. The game colors each level according to a map property at runtime. The parallactic background stalagmites are also tinted to match the level. Here's a screenshot of a level colored red:

Paralaxer's tilemap level 1

Tiled Map Editor

The Tiled map editor is a free, open-source application you can use to draw tilemaps. It uses the .TMX file format, which Cocos2d-X can parse and import into your game.

Download the Tiled editor. It's recommended to grab the latest version available for your system. Note that the screenshots you see in this tutorial are from Tiled version 0.6.1 (because I have an old 1st gen MBP that can't run Lion).

Also download the tilemap image file Rock.png.

A New TMX Tilemap

Open the Tiled application and choose New from the File menu. Choose Orthogonal from the Orientation dropdown. Set the Map size to 32 x 32 and the Tile size to 16 x 16, then click OK.

Creating a new tilemap file with Tiled

Now let's give it the rock tileset so we have something to draw with. Choose New Tileset from the Map menu, then click Browse button next to Image and choose your copy of Rock.png.

Creating a new tileset in Tiled

You'll now have the Rock tileset in your Tilesets window. From this window, you can select a single tile or multiple tiles to draw with:

Selecting tiles for drawing with Tiled

Then go back to your main Tiled window and draw your level. You can use the button that looks like a Stamp to draw, the Paint Bucket to fill and the Eraser to erase:

The tools to draw levels with Tiled

Keep in mind that you can have multiple tilesets per tilemap. However, you have to be careful to only draw using a single tileset per layer. If you accidentally mix tiles from different tilesets in one layer, you will likely cause a crash when you run your game.

Objects

When you're finished drawing the level, it's time to add some objects. Objects can be things like the player, enemies, items and other physical things.

Choose Add Object Layer from the Layers menu, then choose the Insert Objects tool.

The tools to create objects in Tiled

With the Insert Objects tool selected, you can click and drag within your tilemap to create a rectangle representing the object's position and area:

An object in Tiled

Now that the object has been created, you can choose the Select Objects tool, then right-click on your object to edit its properties. Let's give this object the Name & Type "Player". You can also give your player object additional properties, like initial velocity or whatever you like:

Object properties in Tiled

Now save your level file and add it to your game's project.

TMX into Box2d

Loading a TMX file in Cocos2d-X is as easy as creating a CCTMXTiledMap object:

this->map = CCTMXTiledMap::create("Level01.tmx");

That will create the map. Behind the scenes, Cocos2d-X loads the TMX file, parses all the tiles, loads the tileset images and parses the object groups.

You can then create a Box2D fixture for each of the tiles to form a physical world that your player can interact with. Note that we will discuss Box2D in further detail in a later chapter of this book.

void Level::prepareLayers(){   CCARRAY_FOREACH(this->map->getChildren(), object)   {      // is this map child a tile layer?      CCTMXLayer* layer = dynamic_cast<CCTMXLayer*>(object);      if( layer != nullptr )         this->createFixtures(layer);   }}void Level::createFixtures(CCTMXLayer* layer){   // create all the rectangular fixtures for each tile in the level   CCSize layerSize = layer->getLayerSize();   for( int y=0; y < layerSize.height; y++ )   {      for( int x=0; x < layerSize.width; x++ )      {         // create a fixture if this tile has a sprite         CCSprite* tileSprite = layer->tileAt(ccp(x, y));         if( tileSprite )            this->createRectangularFixture(layer, x, y, 1.1f, 1.1f);      }   }}void Level::createRectangularFixture(CCTMXLayer* layer, int x, int y,   float width, float height){   // get position & size   CCPoint p = layer->positionAt(ccp(x,y));   CCSize tileSize = this->map->getTileSize();   const float pixelsPerMeter = 32.0f;   // create the body   b2BodyDef bodyDef;   bodyDef.type = b2_staticBody;   bodyDef.position.Set((p.x + (tileSize.width / 2.0f)) / pixelsPerMeter,      (p.y + (tileSize.height / 2.0f)) / pixelsPerMeter);   b2Body* body = world->CreateBody(&bodyDef);      // define the shape   b2PolygonShape shape;   shape.SetAsBox((tileSize.width / pixelsPerMeter) * 0.5f * width,      (tileSize.width / pixelsPerMeter) * 0.5f * height);      // create the fixture   b2FixtureDef fixtureDef;   fixtureDef.shape = &shape;      fixtureDef.density = 1.0f;   fixtureDef.friction = 0.3f;   fixtureDef.restitution = 0.0f;   fixtureDef.filter.categoryBits = kFilterCategoryLevel;   fixtureDef.filter.maskBits = 0xffff;   body->CreateFixture(&fixtureDef);}

That will create a 16x16 static Box2D fixture with a little bit of friction at each position where you drew a tile.

Creating the Objects

Next it's time to create your game's objects from the object data in the tilemap level.

A CCTMXTiledMap holds a CCArray of CCTMXObjectGroup objects which subsequently hold CCArrays of CCDictionary objects representing the properties of the objects. You can turn this data into new objects in your game by looping over the object groups and the objects they hold:

#define ifDynamicCast(__type__,__var__,__varName__) \   __type__ __varName__ = dynamic_cast<__type__>(__var__); \   if( __varName__ )void Level::addObjects(){   // loop over the object groups in this tmx file   auto groups = map->getObjectGroups();   for( int i = 0; i < groups->count(); i++ )   {      ifDynamicCast(CCTMXObjectGroup*, groups->objectAtIndex(i), group)      {         auto objects = group->getObjects();         for( int j = 0; j < objects->count(); j++ )         {            ifDynamicCast(CCDictionary*, objects->objectAtIndex(j),               properties)            {               ifDynamicCast(CCString*, properties->objectForKey("type"),                  className)               {                  this->addObject(className->getCString(), properties);               }            }         }      }   }}

Multiple Resolutions

Now that we are in the day and age of having to create multiple tiers of art assets for multiple devices, we need a way to turn our SD TMX level file into HD and HDR (HD Retina). Luckily, there's a tool created by WasabiBit calledWBTMXTool which will automatically scale TMX files.

Unfortunately, WasabiBit's website with his development notes are now offline. However, here's a coupleforumposts with more info. The gist is that you can use the commandline tool to scale up your TMX files. Here's an example that scales level01.tmx by 2.0 and outputs to level01-hd.tmx:

WBTMXTool -in level01.tmx -out level01-hd.tmx -scale 2.0 \   -suffixForHD -hd -suffixAction add

You design your level in SD, then convert up to HD and HDR using the tool.

Got questions? Leave a comment below.

Stay tuned. We are writing the next chapter in this free online book. If you'd like, you cansubscribe to be notified when we release new chapters.

原创粉丝点击