TiledMap地圖的使用

/************************************************************************/
/*打開Tiled軟件,新建一個文件,設置寬度和高度,然後添加圖塊(下圖),添加好了後
自己創建地圖,然後保存爲level01.tmx.
*/
/************************************************************************/


 

 

1.在程序中加載tmx文件

CCTMXTiledMap *map = CCTMXTiledMap::create("level01.tmx");

this->addChild(map);


2.使用對象層(設置一個固定的精靈起點)

命名爲objects,

設置對象屬性,

 

在代碼中獲取到X和Y座標的值:

/*加載對象層*/

CCTMXObjectGroup *objGroup = map->objectGroupNamed("objects");

/*加載玩家座標對象*/

CCDictionary* playerPointDic = objGroup->objectNamed("PlayerPoint");

float x = playerPointDic->valueForKey("x")->floatValue();

float y = playerPointDic->valueForKey("y")->floatValue();

/*設置玩家座標*/

m_player->setPosition(ccp(x,y));

 

3.添加障礙物,Tiled障礙層的使用

命名barrier,

此時主角精靈還是能夠越過這個障礙繼續向前,還得建一個meta層,添加新素材meta_tiles.png

選擇第一個方塊,右鍵

然後選中meta層,將剛纔的方塊挨個放在之前的障礙物上面,保存地圖。

 

代碼中如何判斷:

CCPoint tiledCoordForPosition(CCPoint pos)

{

      /*函數功能:將像素座標轉換成地圖格子座標*/

      CCSize mapTiledNum = m_map->getMapSize();//地圖方塊數

      CCSize tiledSize = m_map->getTiledSize();//單個方塊的大小

      int x = pos.x/tiledSize.width;

      int y = (640-pos.y)/tiledSize.height;

      if(x>0){

          x-=1;

      }

      if(y>0){

         y-=0;

      }

      return ccp(x,y);

}


 

void setTagPosition(int x,int y)

{

      /*判斷前方是否不可通行*/

      /*取主角前方的座標*/

      CCSize spriteSize = GetSprite()->getContentSize();

      CCPoint dstPos = CCPoint(x+spriteSize.width/2,y);

      /*獲得相應座標的格子位置*/

      CCPoint tiledPos = tiledCoordForPosition(ccp(dstPos.x,dstPos.y));

      /*獲得格子的唯一標示*/

      CCTMXLayer* meta = m_map->layerNamed("meta");

      meta->setVisible(false);

      meta->retain();

      int tiledGid = meta->tileGIDAt(tiledPos);

      /*不爲0表存在這個格子*/

      if(tiledGid!=0)

      {

              /*這個格子既屬於meta,同時也屬於整個地圖的*/

             CCDictionary* propertiesDict = m_map->propertiesForGID(tiledGid);

             /*取得格子的屬性*/

             const CCString* prop = propertiesDict->valueForKey("Collidable");

             /*判斷Collidable裏面的屬性值是否爲true,如果是,不讓玩家移動*/

             if(prop->m_sString.compare("true")==0){

                     return;

             }

      }

      Entity::setTagPosition(x,y);

      /*以主角爲中心移動地圖*/

      setViewPointByPlayer();

}


 

4.從障礙層清除當前格子的物體

CCTMXLayer* barrier = m_map->layerNamed("barrier");

barrier->removeTileAt(tiledPos);


 

發佈了99 篇原創文章 · 獲贊 21 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章