该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);

上一篇:Python3文件操作1 --Python3


下一篇:【JAVA】类继承对父类静态变量的操作