Tiled地图的简单应用

http://www.cnblogs.com/andyque/archive/2011/04/11/2012852.html

1.地图的创建,我利用的是tiled的软件,仿照上面的博客创建了地图

2.地图的加载,我用的是vs2010和cocos2dx2.0.4版本

tiled = CCTMXTiledMap::create("ortho-objects.tmx");//加载地图

//tiled->setScale(0.8f);

this->addChild(tiled,1,111);

tiled->setPosition(ccp(0,0));

int mapwidth = tiled->getMapSize().width * tiled->getTileSize().width;

int mapheigt = tiled->getMapSize().height *tiled->getTileSize().height;

3.我的主角是一个小人,在地图上面来回运动,动画创建不写了,现在写一下我的左右移动的检测函数,因为瓦片的坐标与屏幕的坐标是不同的,屏幕的坐标是以左下角为原点,但是瓦片的坐标是以左上角为原点坐标,假设地图为m行n列,那么左上角坐标为(0,0),右下角的坐标就为(m-1,n-1)

void Map::playermaphcollision()

{

CCPoint playerpos = gamelayer->getPosition();

CCSize playersize = gamelayer->getContentSize();

CCTMXTiledMap *map = (CCTMXTiledMap*)getChildByTag(111);

int idexx,idexy;

//获取布景层

CCTMXLayer *layer = map->layerNamed("logic");

for (int playery = playerpos.y - playersize.height;playery < playerpos.y;playery++)

{

//主角在左边界

idexx =(playerpos.x-playersize.width/2)/map->getTileSize().width;

idexy =map->getMapSize().height- (playerpos.y/map->getTileSize().height);

CCPoint pos = ccp(idexx,idexy-1);

int titleGid = layer->tileGIDAt(pos);//获取图层元素的gid值

if(titleGid > 0)

{

//CCDictionary的作用就是读取xml的文件的类

CCDictionary *titledic = map->propertiesForGID(titleGid);//根据gid获取xml里面的属性值

if (titledic)

{

CCString *mvalua = (CCString*)titledic->objectForKey("collion");//根据键值获取value的值

if (mvalua)

{

int mv = mvalua->intValue();//转换为我们所需要的类型


if (mv == 2)

{

playerpos.x = (idexx+1)*map->getTileSize().width+playersize.width/2;

gamelayer->setPosition(playerpos);

}

}

}

return;

}

//右移的情况,暂时没右移,可以忽略

idexx = (playerpos.x + playersize.width/2)/map->getTileSize().width;

idexy = map->getMapSize().height- (playerpos.y/map->getTileSize().height);

CCPoint pos1 = ccp(idexx,idexy);

int tilegid = layer->tileGIDAt(pos1);

if (tilegid > 0)

{

CCDictionary *titledic1 = map->propertiesForGID(tilegid);

if (titledic1)

{

CCString *mava1 = (CCString*)titledic1->objectForKey("collion");

int mv1 = mava1->intValue();

if (mv1 == 2)

{

playerpos.x = (idexx-1)*map->getTileSize().width-playersize.width/2;

gamelayer->setPosition(playerpos);

}

}

}

return;


}

}

4.检测碰撞

bool Map::iscollision(CCSprite *mysprite,CCSprite *testsprite)

{

CCPoint ownpos = mysprite->getPosition();

CCPoint otherpos = testsprite->getPosition();

CCSize ownsize = mysprite->getContentSize();

CCSize othersize = testsprite->getContentSize();


CCRect ownrect = CCRectMake(ownpos.x-ownsize.width/2,ownpos.y-ownsize.height/2,ownsize.width,ownsize.height);

CCRect otherrect = CCRectMake(otherpos.x-othersize.width/2,otherpos.y-othersize.height/2,othersize.width,othersize.height);


if (ownrect.intersectsRect(otherrect))

{

return true;

}

return false;

}

这个写法很多


新手一个,有些地方错了,大家给我说一下

你可能感兴趣的:(动画,博客,软件,create,检测)