本文主要是介绍把Tiled中做出的地图弄到项目中~~就是懒,为了以后直接复制写过来,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.现在.h中声明private:cocos2d::CCSprite* ninja;
cocos2d::CCTMXTiledMap* tileMap;
然后.cpp中加入tileMap = CCTMXTiledMap::create("MyTileMap.tmx");
CCTMXLayer* backLayer = tileMap->layerNamed("Tile Layer 1");
CCAssert(backLayer, "Can not find layer named by (Tile Layer 1)");
this->addChild(tileMap); // 地图加到layer上面
2.设置人物的初始位置
CCTMXObjectGroup* og = tileMap->objectGroupNamed("spritePositions");
CCDictionary* posInfoDict = og->objectNamed("ninjaBirthPoint");
int x = posInfoDict->valueForKey("x")->intValue();
int y = posInfoDict->valueForKey("y")->intValue();
ninja = CCSprite::create("Player.png");
ninja->setPosition(ccp(x, y));
tileMap->addChild(ninja);
3.将主角移动到地图的中间
this->setMapPosForView(ccp(x, y));
void HelloWorld::setMapPosForView(cocos2d::CCPoint playerPos){
CCPoint orig = playerPos;
CCPoint dest = ccp(WIN_WIDTH / 2, WIN_HEIGHT / 2);
CCPoint distance = ccpSub(dest, orig);
CCPoint newMapPos = ccp(0, 0) + distance;
newMapPos.x = (newMapPos.x > 0? 0:newMapPos.x);
newMapPos.y = (newMapPos.y > 0? 0:newMapPos.y);
newMapPos.x = (newMapPos.x < WIN_WIDTH - MAP_WIDTH?
WIN_WIDTH-MAP_WIDTH:newMapPos.x);
newMapPos.y = (newMapPos.y < WIN_HEIGHT - MAP_HEIGHT?
WIN_HEIGHT - MAP_HEIGHT:newMapPos.y);
tileMap->setPosition(newMapPos);
5.用:ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)来使物体移动
void HelloWorld::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent){
CCPoint touchPos=pTouch->getLocation();
touchPos=tileMap->convertToNodeSpace(touchPos);
CCPoint origPos=ninjia->getPosition();
CCPoint diff=touchPos-origPos;
CCPoint ninjaDiff = ccp(0, 0);
if (abs(diff.x) > abs(diff.y)){
if (diff.x > 0){
ninjaDiff.x = tileMap->getTileSize().width;
}
else
{
ninjaDiff.x = -tileMap->getTileSize().width;;
}
}
else{
if (diff.y > 0){
ninjaDiff.y = tileMap->getTileSize().height;
}
else
{
ninjaDiff.y = -tileMap->getTileSize().height;
}
}
CCPoint newPos = origPos + ninjaDiff;
ninja->setPosition(newPos);
tileMap->setMapForView(newPos);
这篇关于把Tiled中做出的地图弄到项目中~~就是懒,为了以后直接复制写过来的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!