瓷砖地图学习笔记
最近在学习cocos2d-x的开发,cocos2d-x就是学习资料太少了,靠看cocos2d和test中源码,各种碰壁,今天对瓷砖地图终于了解一些。。泪流满面,留下笔记,主要说自己碰到的问题
首先,瓷砖地图要使用一个Tiled的软件,自行下载之,贴图什么的自己下载之。
在使用Tiled这个软件的时候,我发现我生成的tmx文件会导致程序的崩溃,但使用test中附带的不会,经过比对他们的xml,才发现要把编辑里的参数选项设置成
这样才行啊!默认竟然是zlib的。。咋没有人提示下呢。找了好久
好吧,制作地图什么的在《learn iphone and ipad cocos2d game development》中有,制作好瓷砖地图后,开始使用瓷砖地图吧。
新建什么的就不说了,在init里面开始载入瓷砖地图
CCTMXTiledMap *tileMap = CCTMXTiledMap::tiledMapWithTMXFile("TileMaps/bgTile.tmx") ;
this->addChild(tileMap,-1,5);
这样就算加入了
但是拖曳什么的还没有用啊,果断响应void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
然后实现之
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint touchLoaction = pTouch->locationInView(pTouch->view());
CCPoint preLocation = pTouch->previousLocationInView(pTouch->view());
touchLoaction = CCDirector::sharedDirector()->convertToGL(touchLoaction);
preLocation = CCDirector::sharedDirector()->convertToGL(preLocation);
CCPoint diff = ccpSub(touchLoaction,preLocation);
CCNode* node =this->getChildByTag(5);
CCPoint currentPos = node->getPosition();
node->setPosition( ccpAdd(currentPos, diff) );
}
这段代码没什么好说的,《learn iphone and ipad cocos2d game development》有说明,不过是object-c的, 有差别。
通过在init中添加this->setIsTouchEnabled(true);还有响应和实现void registerWithTouchDispatcher(); 来接受触摸事件。现在,编译就可以拖曳啦
我的图大致是这样子的
比如我们要点绿色植物,来响应,怎么做呢。
添加一个
属性,其实就是在TMX里加拉(其实TMX就是XML啦,你可以各种手动点开来改)
然后再响应并实现touchbegan
bool HelloWorld::ccTouchBegan( CCTouch *pTouch, CCEvent *pEvent )
{
CCPoint touchLoaction = pTouch->locationInView(pTouch->view());
touchLoaction = CCDirector::sharedDirector()->convertToGL(touchLoaction);
CCTMXTiledMap *tileMap = (CCTMXTiledMap *)this->getChildByTag(5);
CCPoint pt = tilePosFromLocation(touchLoaction,tileMap);
CCTMXLayer *layer = tileMap->layerNamed("gameLayer");
int tileId = layer->tileGIDAt(pt);
if (tileId != 0)
{
CCStringToStringDictionary *dictionary = tileMap->propertiesForGID(tileId);
if(dictionary)
{
CCString *isTree = dictionary->objectForKey("isTree");
CCString * str= new CCString("1");
if(isTree != NULL && str!= NULL){
if ( isTree->m_sString == str->m_sString)
{
CCLabelTTF *label = (CCLabelTTF*)this->getChildByTag(7);
label->setString("tree touch!");
}else
{
CCLabelTTF *label = (CCLabelTTF*)this->getChildByTag(7);
label->setString("tree isn't touch!");
}}
else
{
CCLabelTTF *label = (CCLabelTTF*)this->getChildByTag(7);
label->setString("tree isn't touch!");
}
}
}
CCLog("开始");
return true;
}
对了,算触摸位置在瓷砖地图中的位置的这个函数,还没有实现,因为懒所以把helloWorldScene的改改,大家看着helloworld见笑了嘿嘿,这样可以算出触摸点在瓷砖地图中的id
cocos2d::CCPoint HelloWorld::tilePosFromLocation( CCPoint loction,CCTMXTiledMap *tileMap )
{
CCPoint pos = ccpSub(loction,tileMap->getPosition());
pos.x = (int)(pos.x / tileMap->getTileSize().width);
pos.y = (int)((tileMap->getMapSize().height*tileMap->getTileSize().height - pos.y)/tileMap->getTileSize().height);
return pos;
}
好,大功告成
完
PS:第一次写博客园的东西,因为我发现好像cocos2d-x的学习资料很少,虽然个人表达能力很差,不会排版,能力有限,但还是写出来了大家见笑,误喷。代码是我测试过的,如果有错误或者没用,就是哪里漏了。。。多摸索调试吧





浙公网安备 33010602011771号