NS_CC_BEGIN // implementation TMXTiledMap TMXTiledMap * TMXTiledMap::create(const std::string& tmxFile) { TMXTiledMap *ret = new (std::nothrow) TMXTiledMap(); if (ret->initWithTMXFile(tmxFile)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; }
void BattleLayer::_makeAStarData(){ TMXTiledMap *tiledMap = TMXTiledMap::create("res/map/battle_map.tmx"); TMXLayer *walkableLayer = tiledMap->getLayer("walkable"); Size mapSize = walkableLayer->getLayerSize(); // CCLOG("MapSize: (%f, %f)", mapSize.width, mapSize.height); AStarDataNode astarDataVec[20][30]; for (int column = 0; column < _battleMapTileSize.width; ++column){ for (int row = 0; row < _battleMapTileSize.height; ++row){ Vec2 tileCoord = Vec2(column + 5, mapSize.height - (row + 5) - 1); int tileGID = walkableLayer->getTileGIDAt(tileCoord); if (tileGID > 0){ Value value = tiledMap->getPropertiesForGID(tileGID); ValueMap valueMap = value.asValueMap(); int walkable = valueMap["walkable"].asInt(); // CCLOG("Column: %d, Row: %d, Walkable: %d", column, row, walkable); astarDataVec[column][row].column = column; astarDataVec[column][row].row = row; astarDataVec[column][row].walkable = (walkable == 0) ? false : true; } } } for (int column = 0; column < _battleMapTileSize.width; ++column){ std::vector<AStarDataNode> oneList; std::vector<BattleElement *> oneBattleElementList; for (int row = 0; row < _battleMapTileSize.height; ++row){ AStarDataNode astarDataNode = AStarDataNode(column, row, astarDataVec[column][row].walkable); oneList.push_back(astarDataNode); oneBattleElementList.push_back(nullptr); } astarData.push_back(oneList); battleElements.push_back(oneBattleElementList); } // for (int row = 0; row < _battleMapTileSize.height; ++row){ // for (int column = 0; column < _battleMapTileSize.width; ++column){ // printf("%d", astarData[column][row].walkable); // } // printf("\n"); // } }
Point MapLayer::convertTo2d(Point position) { TMXTiledMap* map = (TMXTiledMap*) getChildByTag(kTagTileMap); int mapWidth = map->getMapSize().width * map->getTileSize().width; int mapHeight = map->getMapSize().height * map->getTileSize().height; int x = position.x; int y = position.y; double distanse; double sin1; double sin11; double sin22; double cos11; double cos1; int d2x; int d2y; double mystatic5 = sqrt(5.0); double mystatic = 16 * mystatic5; //char mch[256]; if(x > mapWidth/2){ distanse = sqrt((x - mapWidth/2) * (x - mapWidth/2) + (mapHeight - y) * (mapHeight - y)); sin1 = (mapHeight - y)/distanse; cos1 = (x - mapWidth/2)/distanse; sin11 = (sin1 * 2 - cos1) / mystatic5; cos11 = (sin1 + cos1 * 2) / mystatic5; d2y = distanse * 5 / 4 * sin11 / mystatic; sin22 = (2 * sin1 + cos1) / mystatic5; d2x = distanse * 5 / 4 * sin22 / mystatic; return Point(d2x,d2y); }else{ distanse = sqrt((mapWidth/2 - x) * (mapWidth/2 - x) + (mapHeight - y) * (mapHeight - y)); sin1 = (mapHeight - y)/distanse; cos1 = (mapWidth/2 - x)/distanse; sin11 = (sin1 * 2 - cos1) / mystatic5; cos11 = (sin1 + cos1 * 2) / mystatic5; d2x = distanse * 5 / 4 * sin11 / mystatic; //sin22 = 4.0 * cos11 / 5 + 3.0 * sin11 / 5; sin22 = (2 * sin1 + cos1) / mystatic5; d2y = distanse * 5 / 4 * sin22 / mystatic; return Point(d2x,d2y); } }
//鍔犺浇鏁屼汉琛岃蛋璺緞鐐? void GameScene::initAllPoints() { //寰楀埌tmx鍦板浘 TMXTiledMap* ourMap = (TMXTiledMap*)this->getChildByTag(0); auto Group = ourMap->getObjectGroup("Obj1");//鑾峰彇瀵硅薄灞傛暟鎹? auto Objs = Group->getObjects(); for (auto &eachObj : Objs) { ValueMap& dict = eachObj.asValueMap(); float x = dict["x"].asFloat(); float y = dict["y"].asFloat(); //灏嗗悇涓偣鏁版嵁鎻愬彇骞剁敓鎴怲DPoint TDPoint * newPoint = TDPoint::createPoint(x, y); //灏嗘柊鐢熸垚鐨凾DPoint鍔犲叆鏍? allPoint.pushBack(newPoint); } }
TMXTiledMap* MapLayer::initMapWithFile(const char *name) { TMXTiledMap *tileMap; std::string path; std::string maps("Maps"); auto iterFind = std::find(searchPaths.begin(), searchPaths.end(), maps); if (iterFind == searchPaths.end()) CCAssert(iterFind != searchPaths.end(), "Maps in vector searchPaths not for"); else { path = maps + '/' + name; tileMap = TMXTiledMap::create(path); CCAssert(tileMap != nullptr, "tileMap == NULL"); tileMap->setPosition(Vec2(0, 0)); this->addChild(tileMap); } global->tileMap = tileMap; return tileMap; }
void CRole::updateVertexZ() { do { CBackgroundManager* bkg = getBackGround(); BREAK_IF(nullptr == bkg); TMXTiledMap* map = bkg->getTiledMap(); BREAK_IF(nullptr == map); const Size& szMap = map->getMapSize(); float lowestZ = -(szMap.width + szMap.height); const Point& tilePos = getLogicGrid()->getGridPos(); float currentZ = tilePos.x + tilePos.y; setSpriteVertexZ(lowestZ + currentZ - 1); // setSpriteZOrder(lowestZ + currentZ - 1); } while (false); }
bool GameStart::init() { if (!Layer::init()){ return false; } TMXTiledMap *backGround = TMXTiledMap::create("startbackground.tmx"); backGround->setScale(1.84f); backGround->setPosition(Vec2(20,20)); this->addChild(backGround); MenuItemFont *menuItemFont1 = MenuItemFont::create("Start Game", [](Ref *pSender){ Scene *scene = StageScene::createScene(1,3,3); TransitionProgressRadialCW *transitionProgressRadialCW = TransitionProgressRadialCW::create(0.5f,scene); Director::getInstance()->replaceScene(transitionProgressRadialCW); }); Menu *menu = Menu::create(menuItemFont1, NULL); menu->alignItemsHorizontally(); menu->setPosition(Vec2(FrameSize.width / 2, FrameSize.height / 2 - 120)); this->addChild(menu); return true; }
bool CityScene::init() { if (!Layer::init()) { return false; } char szRound[260]; sprintf(szRound, "Round%d.tmx", mRound); TileMapInfo* tileMapInfo = TileMapInfo::createMapInfoWithFile(szRound); TMXTiledMap* tmxTileMap = tileMapInfo->getTileMap(); this->addChild(tmxTileMap); mPlayerTank[0] = Tank::createTankWithTankType("player2U.png", tileMapInfo); Size tileSize = tmxTileMap->getTileSize(); Size mapSize = tmxTileMap->getContentSize(); mPlayerTank[0]->setPosition(Vec2(mapSize.width / 2 - tileSize.width * 3, tileSize.height)); mLayerPanel = Panel::create(); addChild(mLayerPanel, 3); return true; }
bool MapLayer::init() { bool bRet = false; do { CC_BREAK_IF(!Layer::init()); Size winSize = Director::getInstance()->getWinSize(); // 初始化地图 TMXTiledMap* map = TMXTiledMap::create("iso-test-zorder.tmx"); map->setPosition((winSize.width - map->getContentSize().width)/2, 0); this->addChild(map, 0, kTagTileMap); // 初始化任务 _tamara = Sprite::create("grossinis_sister1.png"); map->addChild(_tamara, map->getChildren().size()); _tamara->retain(); int mapWidth = map->getMapSize().width * map->getTileSize().width; int mapHeight = map->getMapSize().height * map->getTileSize().height; _tamara->setPosition(mapWidth/2, 112); _tamara->setAnchorPoint(Point(0.5f, 0)); _vmove = -1; _hmove = -1; _stepIndex = -1; _myAstar = new Astar(); this->scheduleUpdate(); auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(MapLayer::onTouchBegan, this); this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); bRet = true; } while (0); return bRet; }
void MapAnalysis::initMap(char* levelName) { GameManager* gameManager = GameManager::getInstance(); //¶ÁÈ¡TiledµØͼ×ÊÔ´ TMXTiledMap* tiledMap = TMXTiledMap::create(levelName); gameManager->gameLayer->addChild(tiledMap, -1); //todo--ÊӲ¾°£¬´Ë´¦ÐÞ¸Ä!TODO!ÔÆ²Ê Sprite* could1 = Sprite::create("Items/cloud1.png"); could1->setPosition(500, 500); gameManager->bkLayer->addChild(could1); Sprite* could2 = Sprite::create("Items/cloud2.png"); could2->setPosition(900, 700); gameManager->bkLayer->addChild(could2); Sprite* could3 = Sprite::create("Items/cloud3.png"); could3->setPosition(1400, 450); gameManager->bkLayer->addChild(could3); Sprite* could4 = Sprite::create("Items/cloud1.png"); could4->setPosition(1400 + 500, 500); gameManager->bkLayer->addChild(could4); Sprite* could5 = Sprite::create("Items/cloud2.png"); could5->setPosition(1400 + 700, 700); gameManager->bkLayer->addChild(could5); Sprite* could6 = Sprite::create("Items/cloud3.png"); could6->setPosition(1400 + 1400, 450); gameManager->bkLayer->addChild(could6); //BrickLayer µØ°å Spikes ·æ´Ì TMXObjectGroup* brickLayer = tiledMap->getObjectGroup("BrickLayer"); ValueVector bricks = brickLayer->getObjects(); for (int i = 0; i < bricks.size(); i++) { ValueMap brick = bricks.at(i).asValueMap(); float w = brick.at("width").asFloat(); float h = brick.at("height").asFloat(); float x = brick.at("x").asFloat() + w/2.0f; float y = brick.at("y").asFloat() + h/2.0f; if (brick.at("name").asString() == "Brick")//̨½× { Brick* b = Brick::create(x, y, w, h); gameManager->gameLayer->addChild(b); } else if (brick.at("name").asString() == "Wall")//ǽ { Wall* wa = Wall::create(x, y, w, h); gameManager->gameLayer->addChild(wa); } else if (brick.at("name").asString() == "Spikes")//·æ´Ì { Spikes* sk = Spikes::create(x, y, w, h); gameManager->gameLayer->addChild(sk); } else if (brick.at("name").asString() == "DeadRoof")//ËÀÍǫ̈½× { DeadRoof* dr = DeadRoof::create(x, y, w, h); gameManager->gameLayer->addChild(dr); } } //CoinLayer ½ð±Ò TMXObjectGroup* coinLayer = tiledMap->getObjectGroup("CoinLayer"); ValueVector coins = coinLayer->getObjects(); for (int i = 0; i < coins.size(); i++) { ValueMap coin = coins.at(i).asValueMap(); float w = SD_FLOAT("coin_float_width"); float h = SD_FLOAT("coin_float_height"); float x = coin.at("x").asFloat() + w / 2.0f; float y = coin.at("y").asFloat() + h / 2.0f; Coin* c = Coin::create(x, y, w, h); gameManager->thingLayer->addChild(c); } //MonsterLayer ¹ÖÎï TMXObjectGroup* monsterLayer = tiledMap->getObjectGroup("MonsterLayer"); ValueVector monsters = monsterLayer->getObjects(); for (int i = 0; i < monsters.size(); i++) { ValueMap monster = monsters.at(i).asValueMap(); //MonsterEx ÈËÐ͹ÖÎï if (monster.at("name").asString() == "MonsterEx") { float w = SD_FLOAT("monster_float_width"); float h = SD_FLOAT("monster_float_height"); float x = monster.at("x").asFloat() + w / 2.0f; float y = monster.at("y").asFloat() + h / 2.0f; MonsterEx* m = MonsterEx::create(x, y, w, h); gameManager->monsterLayer->addChild(m); } //FlyingSlime ·ÉÐÐÊ·À³Ä· if (monster.at("name").asString() == "FlyingSlime") { float w = SD_FLOAT("flyingslime_float_width"); float h = SD_FLOAT("flyingslime_float_height"); float x = monster.at("x").asFloat() + w / 2.0f; float y = monster.at("y").asFloat() + h / 2.0f; FlyingSlime* f = FlyingSlime::create(x, y, w, h); gameManager->monsterLayer->addChild(f); } //Slime Ê·À³Ä· if (monster.at("name").asString() == "Slime") { float w = SD_FLOAT("slime_float_width"); float h = SD_FLOAT("slime_float_height"); float x = monster.at("x").asFloat() + w / 2.0f; float y = monster.at("y").asFloat() + h / 2.0f; Slime* s = Slime::create(x, y, w, h); gameManager->monsterLayer->addChild(s); } //£¡£¡£¡Bird Äñ ÖÐÁ¢µÄ--------£¡£¡£¡£¡£¡ if (monster.at("name").asString() == "Bird") { float w = SD_FLOAT("bird_float_width"); float h = SD_FLOAT("bird_float_height"); float x = monster.at("x").asFloat() + w / 2.0f; float y = monster.at("y").asFloat() + h / 2.0f; Bird* b = Bird::create(x, y, w, h); gameManager->monsterLayer->addChild(b); } } //ArticleLayer ½»»¥ÎïÌå TMXObjectGroup* articleLayer = tiledMap->getObjectGroup("ArticleLayer"); ValueVector articles = articleLayer->getObjects(); for (int i = 0; i < articles.size(); i++) { ValueMap article = articles.at(i).asValueMap(); //Article ½»»¥ÎïÌå-Ïä×Ó if (article.at("name").asString() == "Article") { float w = SD_FLOAT("article_float_width"); float h = SD_FLOAT("article_float_height"); float x = article.at("x").asFloat() + w / 2.0f; float y = article.at("y").asFloat() + h / 2.0f; Article* a = Article::create(x, y, w, h); gameManager->thingLayer->addChild(a); } //Door ÃÅ if (article.at("name").asString() == "Door") { float w = SD_FLOAT("door_float_width"); float h = SD_FLOAT("door_float_height"); float x = article.at("x").asFloat() + w / 2.0f; float y = article.at("y").asFloat() + h / 2.0f; Door* a = Door::create(x, y, w, h); gameManager->thingLayer->addChild(a); } //JumpBoard Ìø°å if (article.at("name").asString() == "JumpBoard") { float w = SD_FLOAT("jump_float_width"); float h = SD_FLOAT("jump_float_height"); float x = article.at("x").asFloat() + w / 2.0f; float y = article.at("y").asFloat() + h / 2.0f; JumpBoard* jb = JumpBoard::create(x, y, w, h); gameManager->gameLayer->addChild(jb); } } //HeroLayer Ó¢ÐÛ TMXObjectGroup* heroLayer = tiledMap->getObjectGroup("HeroLayer"); ValueVector heros = heroLayer->getObjects(); for (int i = 0; i < heros.size(); i++) { ValueMap hero = heros.at(i).asValueMap(); //Article ½»»¥ÎïÌå-Ïä×Ó if (hero.at("name").asString() == "Hero") { float w = SD_FLOAT("hero_float_width"); float h = SD_FLOAT("hero_float_height"); float x = hero.at("x").asFloat() + w / 2.0f; float y = hero.at("y").asFloat() + h / 2.0f; Hero* e = Hero::create(x, y, w, h); gameManager->heroLayer->addChild(e); //ÎÞµÐ1Ãë e->setUnbeatable(1); GameManager::getInstance()->hero = e; } } }
void prep::testTMX() { Size visibleSize = Director::getInstance()->getVisibleSize(); //创建游戏 TMXTiledMap* tmx = TMXTiledMap::create("map.tmx"); tmx->setPosition(visibleSize.width / 2, visibleSize.height / 2); tmx->setAnchorPoint(Vec2(0.5, 0.5)); tmx->setName("paopaot"); this->addChild(tmx); //获取对象层 TMXObjectGroup* objects = tmx->getObjectGroup("bubble"); //对应对象层的对象数组 ValueVector container = objects->getObjects(); //遍历 for (auto obj : container) { ValueMap values = obj.asValueMap(); //获取坐标(cocos2dx坐标) int x = values.at("x").asInt(); int y = values.at("y").asInt(); auto buble = Sprite::create("bubble.png"); buble->setPosition(Vec2(x, y + 64)); buble->ignoreAnchorPointForPosition(true); tmx->addChild(buble, 2); prep::bubbles.pushBack(buble); } objects = tmx->getObjectGroup("wall"); container = objects->getObjects(); for (auto obj : container) { ValueMap values = obj.asValueMap(); int x = values.at("x").asInt(); int y = values.at("y").asInt(); auto wall = Sprite::create("wall.png"); wall->setPosition(Vec2(x, y + 64)); wall->ignoreAnchorPointForPosition(true); tmx->addChild(wall, 1); prep::walls.pushBack(wall); } objects = tmx->getObjectGroup("money"); container = objects->getObjects(); for (auto obj : container) { ValueMap values = obj.asValueMap(); int x = values.at("x").asInt(); int y = values.at("y").asInt(); auto goal = Sprite::create("money.png"); goal->setPosition(Vec2(x, y + 64)); goal->ignoreAnchorPointForPosition(true); tmx->addChild(goal, 1); prep::money.pushBack(goal); } objects = tmx->getObjectGroup("player"); container = objects->getObjects(); for (auto obj : container) { ValueMap values = obj.asValueMap(); int x = values.at("x").asInt(); int y = values.at("y").asInt(); auto player = Sprite::create("player.png"); player->setPosition(Vec2(x, y + 64)); player->ignoreAnchorPointForPosition(true); player->setName("player"); tmx->addChild(player, 1); } }
// on "init" you need to initialize your instance bool GamePlaying::init() { _trans=false; _tag=0; ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(GamePlaying::menuCloseCallback, this)); Vec2 menupos = Vec2(origin.x + visibleSize.width, origin.y + closeItem->getContentSize().height/2); menupos.x -=closeItem->getContentSize().width/2; closeItem->setPosition(menupos); //リロード auto reloadItem = MenuItemImage::create( "reload.png", "reload.png", CC_CALLBACK_1(GamePlaying::menuReloadCallback, this)); menupos.x =visibleSize.width/2; reloadItem->setPosition(menupos); //次へ auto nextItem = MenuItemImage::create( "next.png", "next.png", CC_CALLBACK_1(GamePlaying::menuNextCallback, this)); menupos.x =visibleSize.width/2 + nextItem->getContentSize().width*2; nextItem->setPosition(menupos); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, reloadItem ,nextItem, nullptr); menu->setPosition(Vec2::ZERO); this->addChild(menu, 100); int priority=0; _pm = PHYSICSSHAPE_MATERIAL_DEFAULT; _pm.friction = 0.5f; _pm.density = 0.5f; ///////////////////////////// // 3. add your codes below... //背景 auto bg = SpriteBatchNode::create("bg.png"); auto bg2 = SpriteBatchNode::create("bg2.png"); int i=0,j=0; for(int j=0;j<4;++j){ for(int i=0;i<2;++i){ auto sp=Sprite::createWithTexture(bg->getTexture()); sp->setPosition(128+i*256,128+j*256); bg->addChild(sp); auto sp2=Sprite::createWithTexture(bg2->getTexture()); sp2->setPosition(128+i*256,128+j*256); bg2->addChild(sp2); sp2->runAction(RepeatForever::create(Sequence::createWithTwoActions( FadeIn::create(2.5f),FadeOut::create(2.5f) ))); } } addChild(bg); addChild(bg2); TMXTiledMap* tiledmap; TMXMapInfo* mapinfo; if(stage_no==0){ _slushLimit=10; auto label = LabelTTF::create(GetUTF8FromSJIS("チャンスは1度きり…"), "Arial", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, priority++); tiledmap = TMXTiledMap::create("stage1.tmx"); mapinfo = TMXMapInfo::create("stage1.tmx"); }else if(stage_no==2){ _slushLimit=2; auto label = LabelTTF::create(GetUTF8FromSJIS("チャンスは2回のみだ"), "Arial", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, priority++); tiledmap = TMXTiledMap::create("stage2.tmx"); mapinfo = TMXMapInfo::create("stage2.tmx"); }else if(stage_no==2){ _slushLimit=3; #ifdef _WINDOWS auto label = LabelTTF::create(GetUTF8FromSJIS("3回切ってくれたまえ"), "Arial", 24); #else auto label = LabelTTF::create(GetUTF8FromSJIS("3回切ってくれたまえ"),"Arial",24); #endif // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, priority++); tiledmap = TMXTiledMap::create("stage3.tmx"); mapinfo = TMXMapInfo::create("stage3.tmx"); }else{ _slushLimit=3; auto data = cocos2d::FileUtils::sharedFileUtils()->getStringFromFile("String.txt"); auto label = LabelTTF::create(data.c_str()/*("3回ぶった斬れ!!")*/, "MS Pゴシック", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, priority++); tiledmap = TMXTiledMap::create("stage4.tmx"); mapinfo = TMXMapInfo::create("stage4.tmx"); } auto soni=Sprite::create("soniko_t.png"); soni->setScale(0.5); soni->setPosition(250,400); addChild(soni); Vector<TMXTilesetInfo*>& tileset = mapinfo->getTilesets(); TMXTilesetInfo* ts= tileset.at(0); ObjectLayerParse(tiledmap->getObjectGroup("cuttable"),priority); ObjectLayerParse(tiledmap->getObjectGroup("scaffold"),priority); auto director = Director::getInstance(); auto listener=EventListenerTouchOneByOne::create(); listener->onTouchBegan=CC_CALLBACK_2(GamePlaying::onTouchBegan,this); listener->onTouchMoved=CC_CALLBACK_2(GamePlaying::onTouchMoved,this); listener->onTouchEnded=CC_CALLBACK_2(GamePlaying::onTouchEnded,this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this); Director::getInstance()->getTextureCache()->addImage("blade.png"); auto qp=ParticleSystemQuad::create("hellfire.plist"); qp->setPosition(300,0); addChild(qp,10); //auto streak = MotionStreak::create(0.3f,0.01f,30.f,Color3B::WHITE,"trail.png"); //streak->setName("streak"); //streak->setBlendFunc(BlendFunc::ALPHA_PREMULTIPLIED); //addChild(streak); //streak->setBlendFunc(b); //cocos2d::BlendFunc b; //b.dst=GL_ZERO; //b.src=GL_ONE_MINUS_DST_COLOR; // //auto s=Sprite::create(); //s->setTextureRect(Rect(0,0,480,800)); //s->setPosition(240,400); //s->setColor(Color3B::WHITE); //s->setBlendFunc(b); //s->setName("reverse"); //s->setVisible(false); //addChild(s,65535); scheduleUpdate(); return true; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Scene::init() ) { return false; } visibleSize = Director::getInstance()->getVisibleSize(); origin = Director::getInstance()->getVisibleOrigin(); en = false; TMXTiledMap* tmx = TMXTiledMap::create("map.tmx"); tmx->setPosition(visibleSize.width / 2, visibleSize.height / 2); tmx->setAnchorPoint(Vec2(0.5, 0.5)); tmx->setScale(Director::getInstance()->getContentScaleFactor()); this->addChild(tmx, 0); //创建一张贴图 auto texture = Director::getInstance()->getTextureCache()->addImage("$lucia_2.png"); //从贴图中以像素单位切割,创建关键帧 auto frame0 = SpriteFrame::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(0, 0, 113, 113))); //使用第一帧创建精灵 player = Sprite::createWithSpriteFrame(frame0); player->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)); addChild(player, 3); //hp条 Sprite* sp0 = Sprite::create("hp.png", CC_RECT_PIXELS_TO_POINTS(Rect(0, 320, 420, 47))); Sprite* sp = Sprite::create("hp.png", CC_RECT_PIXELS_TO_POINTS(Rect(610, 362, 4, 16))); //使用hp条设置progressBar hp = 100; pT = ProgressTimer::create(sp); pT->setScaleX(90); pT->setAnchorPoint(Vec2(0, 0)); pT->setType(ProgressTimerType::BAR); pT->setBarChangeRate(Point(1, 0)); pT->setMidpoint(Point(0, 1)); pT->setPercentage(hp); pT->setPosition(Vec2(origin.x + 14 * pT->getContentSize().width, origin.y + visibleSize.height - 2 * pT->getContentSize().height)); addChild(pT, 1); sp0->setAnchorPoint(Vec2(0, 0)); sp0->setPosition(Vec2(origin.x + pT->getContentSize().width, origin.y + visibleSize.height - sp0->getContentSize().height)); addChild(sp0, 0); // 静态动画 idle.reserve(1); idle.pushBack(frame0); // 攻击动画 attack.reserve(17); for (int i = 0; i < 17; i++) { auto frame = SpriteFrame::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(113 * i, 0, 113, 113))); attack.pushBack(frame); } // 可以仿照攻击动画 // 死亡动画(帧数:22帧,高:90,宽:79) auto texture2 = Director::getInstance()->getTextureCache()->addImage("$lucia_dead.png"); // Todo dead.reserve(22); for (int i = 0; i < 22; ++i) { auto frame= SpriteFrame::createWithTexture(texture2, CC_RECT_PIXELS_TO_POINTS(Rect(79 * i, 0, 79, 90))); dead.pushBack(frame); } // 运动动画(帧数:8帧,高:101,宽:68) auto texture3 = Director::getInstance()->getTextureCache()->addImage("$lucia_forward.png"); // Todo run.reserve(8); for (int i = 0; i < 8; ++i) { auto frame = SpriteFrame::createWithTexture(texture3, CC_RECT_PIXELS_TO_POINTS(Rect(68 * i, 0, 68, 101))); run.pushBack(frame); } auto w = Label::createWithTTF("W", "fonts/arial.ttf", 36); auto wItem = MenuItemLabel::create(w, CC_CALLBACK_1(HelloWorld::moveWCallback,this)); wItem->setPosition(100, 100); auto s = Label::createWithTTF("S", "fonts/arial.ttf", 36); auto sItem = MenuItemLabel::create(s, CC_CALLBACK_1(HelloWorld::moveSCallback, this)); sItem->setPosition(100, 50); auto a = Label::createWithTTF("A", "fonts/arial.ttf", 36); auto aItem = MenuItemLabel::create(a, CC_CALLBACK_1(HelloWorld::moveACallback, this)); aItem->setPosition(50, 50); auto d = Label::createWithTTF("D", "fonts/arial.ttf", 36); auto dItem = MenuItemLabel::create(d, CC_CALLBACK_1(HelloWorld::moveDCallback, this)); dItem->setPosition(150, 50); auto x = Label::createWithTTF("X", "fonts/arial.ttf", 36); auto xItem = MenuItemLabel::create(x, CC_CALLBACK_1(HelloWorld::moveXCallback, this)); xItem->setPosition(visibleSize.width-50, 100); auto y = Label::createWithTTF("Y", "fonts/arial.ttf", 36); auto yItem = MenuItemLabel::create(y, CC_CALLBACK_1(HelloWorld::moveYCallback, this)); yItem->setPosition(visibleSize.width-100, 50); auto menu = Menu::create(wItem, sItem, aItem, dItem, xItem, yItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); dtime = 160; auto temp = CCString::createWithFormat("%d", dtime); time = Label::createWithTTF(temp->getCString(),"fonts/arial.ttf",36); time->setPosition(visibleSize.width / 2, visibleSize.height - 100); this->addChild(time,1); schedule(schedule_selector(HelloWorld::timeCallback), 1.0f, kRepeatForever, 1.0f); schedule(schedule_selector(HelloWorld::moveCallback), 3.0f, kRepeatForever, 1.0f); sc = 0; UserDefault::getInstance()->setIntegerForKey("score", sc); auto temp1 = CCString::createWithFormat("%d", sc); score = Label::createWithTTF(temp1->getCString(), "fonts/arial.ttf", 36); score->setPosition(visibleSize.width / 2, visibleSize.height - 50); this->addChild(score, 1); auto fac = Factory::getInstance(); for (int i = 0; i < 10; ++i) { Sprite* m = fac->createMonster(); float x1 = random(origin.x, visibleSize.width); float y1 = random(origin.y, visibleSize.height); m->setPosition(x1, y1); this->addChild(m, 3); } return true; }
bool GameMap::loadMap(const int& level) { string fileName = StringUtils::format("map/map_%03d.tmx", level); TMXTiledMap* map = TMXTiledMap::create(fileName); m_map = map; float scale = 1 / Director::getInstance()->getContentScaleFactor(); //GridPos TMXObjectGroup* group = map->getObjectGroup("TowerPos"); ValueVector vec = group->getObjects(); m_gridPos.clear(); m_gridPos.resize(vec.size()); if (!vec.empty()) { int i = 0; for (const auto& v : vec) { const ValueMap& dict = v.asValueMap(); m_gridPos[i] = new GridPos( i, Rect(dict.at("x").asFloat(), dict.at("y").asFloat(), dict.at("width").asFloat(), dict.at("height").asFloat())); i++; } } //计算临近的塔的ID float h = group->getProperty("TowerPosHeight").asFloat() *scale; float w = group->getProperty("TowerPosWidth").asFloat() *scale; float dis = (h + 2)*(h + 2) + (w + 2)*(w + 2); vector<int> GridPosID; for (auto t1 : m_gridPos) { GridPosID.clear(); Point pos = t1->getPos(); for (auto t2 : m_gridPos) { if (t1 != t2 && pos.distanceSquared(t2->getPos())<=dis) { GridPosID.push_back(t2->ID); } } int around[8] = { -1, -1, -1, -1, -1, -1, -1, -1 }; for (auto tid : GridPosID) { Rect rect = m_gridPos[tid]->getRect(); if (rect.containsPoint( Point(pos.x , pos.y + h )))around[North] = tid; else if (rect.containsPoint( Point(pos.x - w, pos.y + h )))around[NorthWest] = tid; else if (rect.containsPoint( Point(pos.x - w, pos.y )))around[West] = tid; else if (rect.containsPoint( Point(pos.x - w, pos.y - h )))around[SouthWest] = tid; else if (rect.containsPoint( Point(pos.x , pos.y - h )))around[South] = tid; else if (rect.containsPoint( Point(pos.x + w, pos.y - h )))around[SouthEast] = tid; else if (rect.containsPoint( Point(pos.x + w, pos.y )))around[East] = tid; else if (rect.containsPoint( Point(pos.x + w, pos.y + h )))around[NorthEast] = tid; } t1->setAroundGridPosID(around); } //MonsterPath group = map->getObjectGroup("Path"); vec = group->getObjects(); MonsterPath.clear(); if (!vec.empty()) { vector<Point> posvec; for (const auto& var : vec) { posvec.clear(); const ValueMap& dict = var.asValueMap(); const ValueVector& vec2 = dict.at("polylinePoints").asValueVector(); Point pos = Point(dict.at("x").asFloat(), dict.at("y").asFloat()); for (const auto& v : vec2) { const ValueMap& dict = v.asValueMap(); posvec.push_back(Point(pos.x + dict.at("x").asFloat()*scale, pos.y - dict.at("y").asFloat()*scale)); //posvec.push_back(Point(pos.x + dict.at("x").asFloat(), pos.y - dict.at("y").asFloat())); } MonsterPath.push_back(MapPath(dict.at("LoopTo").asInt(), posvec)); } } //WaveData int waveCount= map->getProperty("WaveCount").asInt(); std::stringstream ss; string propertyName; WaveList.clear(); for (int i = 1; i <= waveCount; i++) { propertyName = StringUtils::format("Wave%03d", i); group = map->getObjectGroup(propertyName); CCASSERT(group != nullptr, string("propertyName :" + propertyName +" NOT found").c_str()); Wave wave; wave.WaveTime = group->getProperty("waveTime").asInt(); int momsterCount = group->getProperty("momsterCount").asInt(); for (int j = 1; j <=momsterCount; j++) { propertyName = StringUtils::format("m%03d", j); ss.clear(); ss << group->getProperty(propertyName).asString(); WaveData data; ss >> data.MonsterID; ss >> data.PathID; ss >> data.NextDalay; wave.wavedata.push_back(data); } WaveList.push_back(wave); } return true; }
PushBoxScene::PushBoxScene() { TMXTiledMap* mytmx = TMXTiledMap::create("Pushbox/map.tmx"); mytmx->setPosition(visibleSize.width / 2, visibleSize.height / 2); mytmx->setAnchorPoint(Vec2(0,0)); myx = (visibleSize.width - mytmx->getContentSize().width) / 2; myy = (visibleSize.height - mytmx->getContentSize().height) / 2; this->addChild(mytmx, 0); count = 0; success = 0; /*mon = Sprite::create("Pushbox/player.png"); mon->setAnchorPoint(Vec2(0, 0)); mon->setPosition(Vec2(SIZE_BLOCK*1+myx, SIZE_BLOCK*8+myy)); mon->setTag(TAG_PLAYER); this->addChild(mon, 1);*/ TMXObjectGroup* objects = mytmx->getObjectGroup("wall"); //从对象层中获取对象数组 ValueVector container = objects->getObjects(); //遍历对象 for (auto obj : container) { ValueMap values = obj.asValueMap(); int x = values.at("x").asInt(); int y = values.at("y").asInt(); Sprite* temp = Sprite::create("Pushbox/wall.png"); temp->setAnchorPoint(Point(0, 0)); temp->setPosition(Point(x,y+64)); mywall.pushBack(temp); this->addChild(temp, 1); } TMXObjectGroup* objects1 = mytmx->getObjectGroup("box"); //从对象层中获取对象数组 ValueVector container1 = objects1->getObjects(); //遍历对象 for (auto obj : container1) { ValueMap values = obj.asValueMap(); int x = values.at("x").asInt(); int y = values.at("y").asInt(); Sprite* temp = Sprite::create("Pushbox/box.png"); temp->setAnchorPoint(Point(0, 0)); temp->setPosition(Point(x, y+64)); mybox.pushBack(temp); this->addChild(temp, 3); } TMXObjectGroup* objects2 = mytmx->getObjectGroup("player"); //从对象层中获取对象数组 ValueVector container2 = objects2->getObjects(); //遍历对象 for (auto obj : container2) { ValueMap values = obj.asValueMap(); int x = values.at("x").asInt(); int y = values.at("y").asInt(); Sprite* temp = Sprite::create("Pushbox/player.png"); temp->setAnchorPoint(Point(0, 0)); temp->setPosition(Point(x, y+64)); mon = temp; this->addChild(temp, 2); } TMXObjectGroup* objects3 = mytmx->getObjectGroup("goal"); //从对象层中获取对象数组 ValueVector container3 = objects3->getObjects(); //遍历对象 for (auto obj : container3) { ValueMap values = obj.asValueMap(); int x = values.at("x").asInt(); int y = values.at("y").asInt(); Sprite* temp = Sprite::create("Pushbox/goal.png"); temp->setAnchorPoint(Point(0, 0)); temp->setPosition(Point(x, y+64)); mygoal.pushBack(temp); this->addChild(temp, 1); } }
void LDZGameLayer::initLevel(int level){ Size vs = Director::getInstance()->getVisibleSize(); Vec2 vo = Director::getInstance()->getVisibleOrigin(); _mode = MODE_BEGAIN; TMXTiledMap *map = TMXTiledMap::create("back.tmx"); _map = map; _mapSize = Size(map->getMapSize().width * map->getTileSize().width , map->getMapSize().height * map->getTileSize().height); map->setPosition(Vec2(0, 0)); this->addChild(map); //main char _mainC = Sprite::createWithSpriteFrameName("1.png"); _mainC->setPosition(_mapSize.width/2, _mainC->getContentSize().height/2 + 10); this->addChild(_mainC,1); //progress auto progress = ProgressTimer::create(Sprite::createWithSpriteFrameName("tempb.png")); float progx = _mapSize.width/2 - _mainC->getContentSize().width/2 - progress->getContentSize().width/2 - 5; float progy = _mainC->getContentSize().height/2 + 10; progress->setPosition( progx, progy); progress->setType(cocos2d::ProgressTimer::Type::BAR); progress->setBarChangeRate(Vec2(0, 1)); progress->setMidpoint(Vec2(0, 0)); auto progback = Sprite::createWithSpriteFrameName("temp.png"); progback->setPosition(progx, progy); this->addChild(progback); this->addChild(progress,1); progress->setVisible(false); progback->setVisible(false); _powerProg = progress; _powerProgBack = progback; //limit float height = 50 + arc4random()%100; float uy = _mapSize.height/3 + _mapSize.height/3*2*CCRANDOM_0_1() - 5; float dy = uy - height; _upLimit = Sprite::createWithSpriteFrameName("limit.png"); _upLimit->setPosition(_mapSize.width/2, uy); this->addChild(_upLimit); _downLimit = Sprite::createWithSpriteFrameName("limit.png"); _downLimit->setPosition(_mapSize.width/2, dy); this->addChild(_downLimit); //guide auto gt = ui::Text::create(LHLocalizedCString("guidetext"), Common_Font, 25); gt->setColor(Color3B::RED); gt->setPosition(Vec2(_mainC->getPosition().x , _mainC->getBoundingBox().getMaxY() + gt->getContentSize().height/2)); this->addChild(gt); auto bl = Blink::create(1, 1); auto rp = RepeatForever::create(bl); gt->runAction(rp); auto da = Sprite::create("da.png"); da->setScaleY(height/da->getContentSize().height); da->setPosition(Vec2(_mainC->getPosition().x,_downLimit->getPositionY()+height/2)); this->addChild(da); auto lis = EventListenerTouchOneByOne::create(); lis->onTouchBegan = [this,gt,progress,progback,da](Touch* tmpTouch, Event*){ if (_mode == MODE_VIEW) { Vec2 loca = tmpTouch->getLocation(); loca = this->convertToNodeSpace(loca); if (_mainC->getBoundingBox().containsPoint(loca)) { CallFunc *call = CallFunc::create([this](){ _mode = MODE_POWER; this->scheduleUpdate(); CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("wiso.wav"); }); float focusMargin = 20; this->focusOn(_mainC->getPosition(), _mainC->getContentSize().height + focusMargin, true , call); _mode = MODE_BEGAIN; gt->removeFromParent(); da->removeFromParent(); progress->setVisible(true); progback->setVisible(true); progress->setPercentage(0); } }else if (_mode == MODE_POWER_END){ _mode = MODE_POWER; } return true; }; lis->onTouchMoved = [this](Touch* tmpTouch, Event*){ Vec2 cu = tmpTouch->getLocation(); Vec2 last = tmpTouch->getPreviousLocation(); if (_mode == MODE_VIEW) { float toy = _focusCenter.y + (last.y - cu.y); if (toy+_focusLen/2 > _upLimit->getPositionY() + 20) { toy = _upLimit->getPositionY()+20 - _focusLen/2; } this->focusOn(Vec2(_focusCenter.x , toy),_focusLen, false); }else if (_mode == MODE_POWER){ float dy = fabsf(cu.y - last.y); _powerProg->setPercentage(_powerProg->getPercentage()+dy/(_powerProg->getPercentage()+1)/MOVE_FACTOR); } }; lis->onTouchEnded = [this](Touch*, Event*){ if (_mode == MODE_POWER) { _mode = MODE_POWER_END; _powerCount = 0.1f; } }; this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(lis, this); focusOn(Vec2(_mapSize.width/2,(uy - height/2)), vs.width, false); auto dl2 = DelayTime::create(1); CallFunc *call = CallFunc::create([this](){ auto tmpcall = CallFunc::create([this](){ _mode = MODE_VIEW; }); this->focusOn(_mainC->getPosition(), _focusLen, true , tmpcall); }); auto sq = Sequence::create(dl2,call, NULL); this->runAction(sq); }
Node* GameMapReader::createNodeWithFlatBuffers(const flatbuffers::Table *gameMapOptions) { TMXTiledMap* tmx = nullptr; auto options = (GameMapOptions*)gameMapOptions; auto fileNameData = options->fileNameData(); bool fileExist = false; std::string errorFilePath = ""; std::string path = fileNameData->path()->c_str(); int resourceType = fileNameData->resourceType(); switch (resourceType) { case 0: { if (FileUtils::getInstance()->isFileExist(path)) { fileExist = true; } else { errorFilePath = path; fileExist = false; } break; } default: break; } if (fileExist) { /* Whether tileset is valid. */ auto mapInfo = TMXMapInfo::create(path); auto& layers = mapInfo->getLayers(); bool valid = false; std::string layerName = ""; for (const auto &layerInfo : layers) { valid = false; if (layerInfo->_visible) { Size size = layerInfo->_layerSize; auto& tilesets = mapInfo->getTilesets(); if (tilesets.size()>0) { TMXTilesetInfo* tileset = nullptr; for (auto iter = tilesets.crbegin(); iter != tilesets.crend(); ++iter) { tileset = *iter; if (tileset) { for( int y=0; y < size.height; y++ ) { for( int x=0; x < size.width; x++ ) { int pos = static_cast<int>(x + size.width * y); int gid = layerInfo->_tiles[ pos ]; if( gid != 0 ) { if( (gid & kTMXFlippedMask) >= tileset->_firstGid ) { valid = true; break; } } } if (valid) { break; } } } } } if (!valid) { layerName = layerInfo->_name; break; } } else { valid = true; } } if (!valid) { Node* node = Node::create(); setPropsWithFlatBuffers(node, (Table*)gameMapOptions); auto label = Label::create(); label->setString(__String::createWithFormat("Some error of gid are in TMX Layer '%s'", layerName.c_str())->getCString()); node->setScale(1.0f); node->addChild(label); return node; } /**/ tmx = TMXTiledMap::create(path); if (tmx) { //prevent that editor's data does not match in size and resources Size fileSize = tmx->getContentSize(); setPropsWithFlatBuffers(tmx, (Table*)gameMapOptions); tmx->setContentSize(fileSize); } } else { Node* node = Node::create(); setPropsWithFlatBuffers(node, (Table*)gameMapOptions); return node; } return tmx; }