void Predator::loadFramesFromDataFile(const char *framesDataKey){ ValueMap framesData = DataManager::getInstance()->_staticData\ .at("character").asValueMap()\ .at("predator").asValueMap()\ .at(Value(_id).asString().c_str()).asValueMap()\ .at("frames").asValueMap()\ .at(framesDataKey).asValueMap(); std::string spriteFrameNamePrefix = framesData.at("spriteframe_name_prefix").asString(); int frameNum = framesData.at("frame_num").asInt(); int frameIndexStart = this->_frames.size(); _animationsFrameIndexStart[std::string(framesDataKey)] = frameIndexStart; float frameAnchorPointX = framesData.at("frame_anchor_point_x").asFloat(); float frameAnchorPointY = framesData.at("frame_anchor_point_y").asFloat(); for (int index = 0; index < frameNum; index++) { auto spriteFrameName =String::createWithFormat("%s_%02d.png", spriteFrameNamePrefix.c_str(), index+1); this->_frames[frameIndexStart + index]=Sprite::createWithSpriteFrameName(spriteFrameName->getCString())->getSpriteFrame(); this->_frames[frameIndexStart + index]->retain(); _framesAnchorPoint[frameIndexStart + index] = Point(frameAnchorPointX, frameAnchorPointY); } }
void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary,const std::string& plist) { if ( dictionary.find("animations") == dictionary.end() ) { CCLOG("cocos2d: AnimationCache: No animations were found in provided dictionary."); return; } const Value& animations = dictionary.at("animations"); unsigned int version = 1; if( dictionary.find("properties") != dictionary.end() ) { const ValueMap& properties = dictionary.at("properties").asValueMap(); version = properties.at("format").asInt(); const ValueVector& spritesheets = properties.at("spritesheets").asValueVector(); for(const auto &value : spritesheets) { std::string path = FileUtils::getInstance()->fullPathFromRelativeFile(value.asString(),plist); SpriteFrameCache::getInstance()->addSpriteFramesWithFile(path); } } switch (version) { case 1: parseVersion1(animations.asValueMap()); break; case 2: parseVersion2(animations.asValueMap()); break; default: CCASSERT(false, "Invalid animation format"); } }
void Player::setTagPosition(int x, int y){ auto spriteSize = m_node->getContentSize(); Vec2 dstPos = Vec2(x + spriteSize.width / 2, y); Vec2 tiledPos = tileCoorForPosition(Vec2(dstPos.x, dstPos.y)); int tiledGid = meta->getTileGIDAt(tiledPos); if (tiledGid != 0){ Value properties = m_map->getPropertiesForGID(tiledGid); ValueMap propertiesMap = properties.asValueMap(); if (propertiesMap.find("Collidable") != propertiesMap.end()){ Value prop = propertiesMap.at("Collidable"); if (prop.asString().compare("true") == 0){ return; } } if (propertiesMap.find("food") != propertiesMap.end()){ Value prop = propertiesMap.at("food"); if (prop.asString().compare("true") == 0){ TMXLayer* barrier = m_map->getLayer("barrier"); barrier->removeTileAt(tiledPos); } } } Entity::setTagPosition(x, y); setViewPointByPlayer(); }
//获取Object对象坐标 Vec2 TwoScene::getObjectByName(std::string Layername, std::string name) { //获取对象层 auto objects = _tileMap2->getObjectGroup(Layername); //获取对象信息 ValueMap map = objects->getObject(name); //返回地图中坐标值 return Vec2(map.at("x").asInt(), map.at("y").asInt()); }
void Predator::loadAnimationFromDataFile(const char* animationDataKey){ ValueMap framesData = DataManager::getInstance()->_staticData\ .at("character").asValueMap()\ .at("hamster").asValueMap()\ .at(Value(_id).asString().c_str()).asValueMap()\ .at("animations").asValueMap()\ .at(animationDataKey).asValueMap(); int animationId = _animationsId.size(); _animationsId[std::string(animationDataKey)] = animationId; int animationFrameNum = framesData.at("animation_frame_num").asInt(); bool isAnimationLooping = framesData.at("loop").asBool(); //判断framesData中是否存有"animation_frame_index_start"的信息 bool doesDataIncludeFrameIndexStart = false; for (auto it = framesData.begin(); it != framesData.end(); it++){ if (it->first == std::string("animation_frame_index_start")){ doesDataIncludeFrameIndexStart = true; } } int animationFrameIndexStart; if (doesDataIncludeFrameIndexStart){ animationFrameIndexStart = _animationsFrameIndexStart[std::string(framesData.at("animation_frame_index_start").asString())]; } else{ animationFrameIndexStart = _animationsFrameIndexStart[std::string(animationDataKey)]; } ValueMap animationFrameSequence = framesData.at("animation_frame_sequence").asValueMap(); ValueMap animationDurationSequence = framesData.at("animation_duration_sequence").asValueMap(); _animationFrameSequences[animationId] = new int[animationFrameNum + 1]; _animationDurationSequences[animationId] = new int[animationFrameNum]; for (int animationFrameIndex = 0; animationFrameIndex < animationFrameNum; animationFrameIndex++){ _animationFrameSequences[animationId][animationFrameIndex] = animationFrameSequence[Value(animationFrameIndex).asString().c_str()].asInt() + animationFrameIndexStart; _animationDurationSequences[animationId][animationFrameIndex] = animationDurationSequence[Value(animationFrameIndex).asString().c_str()].asInt(); } if (isAnimationLooping){ _animationFrameSequences[animationId][animationFrameNum] = -1;//循环动画序列结尾标志 } else{ _animationFrameSequences[animationId][animationFrameNum] = -2;//非循环动画序列结尾标志 } }
void AttackMapLayer::addMapMenu(){ //以下全部为设置地图的窗口 TMXTiledMap * changeMap = TMXTiledMap::create("bakground(1).tmx"); this->addChild(changeMap); float cmX = (vSize.width - changeMap->getContentSize().width) / 2; changeMap->setPosition(Vec2(cmX, 0)); TMXObjectGroup * objectgroup = changeMap->getObjectGroup("object"); ValueMap valuemap = objectgroup->getObject("object1"); float x = valuemap.at("x").asFloat(); float y = valuemap.at("y").asFloat(); auto menuitem = MenuItemImage::create("stage-9.png", "stage-9.png", CC_CALLBACK_1(AttackMapLayer::changeMap_a_1, this)); menuitem->setPosition(Vec2(x, y)); auto menu = Menu::create(menuitem, NULL); menu->setPosition(Vec2(cmX, 0)); //房后闪光 auto flashBG = Sprite::create("crusade_stage_7_curren.png"); flashBG->setPosition(Vec2(x , y)); //动画渐入渐出 auto flashAnimationOut = FadeOut::create(0.5); auto flashAnimationIn = FadeIn::create(0.5); auto seqAction = Sequence::create(flashAnimationOut, flashAnimationIn, NULL); flashBG->runAction(RepeatForever::create(seqAction)); addChild(flashBG); valuemap = objectgroup->getObject("object2"); x = valuemap.at("x").asFloat(); y = valuemap.at("y").asFloat(); auto menuitem1 = MenuItemImage::create("stage-19.png", "stage-19.png", CC_CALLBACK_1(AttackMapLayer::changeMap_a_2, this)); menuitem1->setPosition(Vec2(x, y)); menu->addChild(menuitem1); valuemap = objectgroup->getObject("object3"); x = valuemap.at("x").asFloat(); y = valuemap.at("y").asFloat(); auto menuitem2 = MenuItemImage::create("stage-23.png", "stage-23.png", CC_CALLBACK_1(AttackMapLayer::changeMap_a_3, this)); menuitem2->setPosition(Vec2(x, y)); menu->addChild(menuitem2); valuemap = objectgroup->getObject("object4"); x = valuemap.at("x").asFloat(); y = valuemap.at("y").asFloat(); auto menuitem3 = MenuItemImage::create("stage-25.png", "stage-25.png", CC_CALLBACK_1(AttackMapLayer::changeMap_a_4, this)); menuitem3->setPosition(Vec2(x, y)); menu->addChild(menuitem3); this->addChild(menu); }
void SimplePlatformerScene::drawCollisionTiles() { TMXLayer* collisionLayer = _tileMapNode->getLayer("edgeLayer"); auto mapSize = _tileMapNode->getMapSize(); auto tileSize = _tileMapNode->getTileSize(); Sprite* tile = nullptr; Point pos; for(int i = 0; i < mapSize.width; i++) { for(int j = 0; j < mapSize.height; j++) { tile = collisionLayer->getTileAt(Point(i, j)); if(tile != nullptr) { const ValueMap property = _tileMapNode->getPropertiesForGID(collisionLayer->getTileGIDAt(Point(i, j))).asValueMap(); bool collidable = property.at("collidable").asBool(); if(collidable) { pos = collisionLayer->getPositionAt(Point(i, j)); makeBoxObjAt(tile, tileSize, false, PhysicsMaterial(0.2f, 0.5f, 0.5f)); } } } } }
void TollgateScene::addPlayer(TMXTiledMap* map){ Player::delPlayer(); TMXObjectGroup* objGroup = map->getObjectGroup("objects"); ValueMap playerPointMap = objGroup->getObject("PlayerPoint"); float playerX = playerPointMap.at("x").asFloat(); float playerY = playerPointMap.at("y").asFloat(); auto num = CsvUtil::getInstance()->getInt(1, 1, "Tollgate/Player.csv"); auto hp = CsvUtil::getInstance()->getInt(1, 2, "Tollgate/Player.csv"); auto atk = CsvUtil::getInstance()->getInt(1, 3, "Tollgate/Player.csv"); auto speed = CsvUtil::getInstance()->getInt(1, 4, "Tollgate/Player.csv"); auto bullet = CsvUtil::getInstance()->getInt(1, 5, "Tollgate/Player.csv"); m_player = Player::create(Tank::createWithNum(num)); m_player->setAtk(atk); m_player->setHP(hp); m_player->setTiledMap(map); m_player->setSpeed(speed); m_player->setBullet(bullet); m_player->setMaxHP(hp); map->addChild(m_player, 10); auto moveController = FourDirectionMoveController::create(); this->addChild(moveController); m_player->setController(moveController); m_player->setTagPosition(playerX, playerY); }
//获取坐标点 void MapLayer::initPointsVector(float offX){ Node* runOfPoint = nullptr; //1 int count = 1; ValueMap point; //2 while (count<5) { point = object->getObject(std::to_string(count)); //3 auto x = point.at("x").asFloat(); auto y = point.at("y").asFloat(); //4 runOfPoint = Node::create(); runOfPoint->setPosition(Vec2(x + offX , y)); this->pointsVector.pushBack(runOfPoint); //point = object->getObject(std::to_string(count)); count++; runOfPoint = nullptr; } }
void PlayLayer::initPointsVector(float offX) { Node *runOfPoint = NULL; int count = 0; ValueMap point; //by char countBuf1[16] = ""; sprintf(countBuf1, "%d", count); auto moneyText = countBuf1; //point = objects->getObject(std::to_string(count)); point = objects->getObject(moneyText); while (point.begin()!= point.end()) { float x = point.at("x").asFloat(); float y = point.at("y").asFloat(); runOfPoint = Node::create(); runOfPoint->setPosition(Point(x - offX, y )); this->pointsVector.pushBack(runOfPoint); count++; //by char countBuf2[16] = ""; sprintf(countBuf2, "%d", count); auto moneyText = countBuf2; //point = objects->getObject( std::to_string(count)); point = objects->getObject( moneyText); } runOfPoint = NULL; }
/*@return the highest layer could build, otherwise NONE */ int MapModel::canBuildOnTilePosition(Point pos){ Point TileLoc = tileCoordForPosition(pos); //@debug modify label. { char buffer[30]; sprintf(buffer, "row:%.0f, col:%.0f", TileLoc.x, TileLoc.y); //getlblTilePos()->setString(buffer); } //@var later need to Resoucre Manager PFComponent *target = nullptr; if (_status == HUD_ID::DEFENSE) target = Building::build(selID); if (_status == HUD_ID::ATTACK) target = Troop::addTroop(selID); CCASSERT(target != nullptr, "target != nullptr"); for (int lr = SZ(_pfLayers) - 1; lr >= 0; lr--){ Point buildingLoc = mapCoordForPosition(pos, lr); //@procedure check for no tiles on the tile. bool noTileOnDirectly = true; if (lr < SZ(_pfLayers) - 1){ for (int tr = 0; tr < target->getOccupy().X; tr++) for (int tc = 0; tc < target->getOccupy().Y; tc++){ for (int offset = 0; offset <= 1; offset++){ Point checkTileLoc = Point(TileLoc.x + tr, TileLoc.y - tc * 2 + offset); if (isTileInsideLayer(checkTileLoc, lr)){ int tileGid = _pfLayers.at(lr + 1)->getTileGIDAt(checkTileLoc); if (tileGid != EMPTY_TILE) noTileOnDirectly = false; } } } } if (!noTileOnDirectly) continue; int couldTileCnt = 0; for (int tr = 0; tr < target->getOccupy().X; tr++) for (int tc = 0; tc < target->getOccupy().Y; tc++){ for (int offset = 1; offset <= 2; offset++){ Point checkTileLoc = Point(TileLoc.x + tr, TileLoc.y - tc * 2 + offset); if (isTileInsideLayer(checkTileLoc, lr)){ int tileGid = _pfLayers.at(lr)->getTileGIDAt(checkTileLoc); Value props = _tileMap->getPropertiesForGID(tileGid); if (!props.isNull()){ ValueMap map = props.asValueMap(); int type_int = 0; if (map.size() == 0) type_int = 0; else type_int = map.at("buildable").asInt(); if (1 == type_int){ couldTileCnt++; break; } } } } } if (couldTileCnt == target->getOccupy().X*target->getOccupy().Y) return lr + 1; } return -1; }
void taskLayer::testMessage(Ref * message) { BaseSprite * sprite = dynamic_cast<BaseSprite *> (message); std::string name = sprite->getM_name(); ValueMap taskMap = DataXML::getInstence()->getTask(); for (auto taskName : taskMap) { std::string taskKey = taskName.first.c_str(); if (name == taskKey) { for(auto v :allCondition){ std::string key = v.first.c_str(); if (name == key && allCondition.at(name).asInt() < taskMap.at(name).asInt()) { //增加吃到道具数量达到任务要求后的处理!!!!!!!!!!!!!!!!!!!!别忘了 int number = allCondition.at(name).asInt() + 1; allCondition[key] = number; //更改Label显示,更换黄匡 changeDisplay(name); } } } } }
MyTeleport::MyTeleport(const ValueMap &dict, int x, int y) { Point position = Point(x, y); //取得目标地图的层数 key = "targetMap"; targetMap = dict.at(key).asInt(); //获取image项 key = "image"; imagePath = dict.at(key).asString(); //创建用于显示Teleport的精灵 teleportSprite = Sprite::create(imagePath); teleportSprite->setAnchorPoint(Point::ZERO); teleportSprite->setPosition(position) gameLayer->addChild(teleportSprite, kZTeleport); }
void PreLoad::onEnterTransitionDidFinish(){ //调用父类的OnEnterTransitionDidFinish方法 Layer::onEnterTransitionDidFinish(); //加载preloadResources.plist配置文件,读取文件中的游戏资源名称列表,返回一个ValueMap对象 ValueMap map = FileUtils::getInstance()->getValueMapFromFile("preloadResources.plist"); //通过key值取出每种不同类型资源的ValueVector数组 ValueVector spriteSheets = map.at("SpriteSheets").asValueVector(); ValueVector effects = map.at("Sounds").asValueVector(); ValueVector musics = map.at("Musics").asValueVector(); //多个ValueVector数组的size相加得到需要加载的资源总数量 _sourceCount = spriteSheets.size() + effects.size() + musics.size(); //设置进度条更新进度=100 /_sourceCount _progressInterval = 100 / _sourceCount; //依次加载资源 loadMusic(musics); loadEffect(effects); loadSpriteSheets(spriteSheets); }
bool GameWorld::checkCollision(int tileGID) { if (tileGID > 0) { ValueMap tileValues = _tileMap->getPropertiesForGID(tileGID).asValueMap(); CCString* testme = new CCString(); *testme = tileValues.at("Collidable").asString(); if ((testme->length()) > 0 && (testme->compare("True") == 0)) { return true; } } return false; }
bool OrcBoss::initBoss(int wallNode, Node *parent) { _bossName = Value("Orc").asString(); _wallNode = wallNode; this->setPosition(Vec2(SCREEN.width + 150, SCREEN.height * 0.5)); _parent = parent; _showSprite = Sprite::create(); this->addChild(_showSprite); ValueMap bossMap = FileUtils::getInstance()->getValueMapFromFile(MONSTERTYPE_PLIST_NAME).at(_bossName.c_str()).asValueMap(); _givenGold = bossMap.at("given_gold").asInt(); _givenJewel = bossMap.at("given_jewel").asInt(); _knockbackResistance = bossMap.at("knockback_resistance").asFloat(); _attack = bossMap.at("monster_attacka").asInt(); _speed = bossMap.at("monster_speed").asInt(); _hp = bossMap.at("monster_hp").asInt(); _maxHp = _hp; _controller = OrcBossController::createController(this, _wallNode, _parent); this->addChild(_controller); this->setState(BossState::RUN); Sprite *hpBG = Sprite::create("EnemyHPPanel.png"); this->addChild(hpBG, 0, "hpBG"); hpBG->setPositionY(-100); _hpPanel = Sprite::create("EnemyHP.png"); this->addChild(_hpPanel, 1, "hpPanel"); _hpPanel->setPositionY(-100); return true; }
void GameManager::initRes() { std::string path = FileUtils::getInstance()->fullPathForFilename("load.xml"); ValueMap vm = FileUtils::getInstance()->getValueMapFromFile(path); for (int i = 0; i < vm.size(); i++) { char buf[12]; sprintf(buf, "%d", i+1); std::string s = vm.at(buf).asString(); SpriteFrameCache::getInstance()->addSpriteFramesWithFile(s); } vm.clear(); }
bool EventTrigger::init( class MapLogic* map_logic, const ValueMap& event_data ) { this->setMapLogic( map_logic ); _current_trigger_index = 0; _should_recycle = false; _event_data = event_data; const ValueMap& meta_data = event_data.at( "trigger_meta" ).asValueMap(); auto itr = meta_data.find( "trigger_relation" ); if( itr == meta_data.end() ) { _relation = "then"; } else { _relation = itr->second.asString(); } itr = meta_data.find( "is_repeated" ); if( itr == meta_data.end() ) { _is_repeat = false; } else { _is_repeat = itr->second.asBool(); } itr = event_data.find( "enabled" ); if( itr != event_data.end() ) { this->setEnabled( itr->second.asBool() ); } else { this->setEnabled( true ); } const ValueVector& trigger_data = event_data.at( "triggers" ).asValueVector(); _total_trigger_count = (int)trigger_data.size(); for( auto itr = trigger_data.begin(); itr != trigger_data.end(); ++itr ) { Trigger* trigger = Trigger::create( itr->asValueMap() ); this->addTrigger( trigger ); } return true; }
void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dict, const std::string &texturePath) { std::string pixelFormatName; if (dict.find("metadata") != dict.end()) { ValueMap& metadataDict = dict.at("metadata").asValueMap(); if (metadataDict.find("pixelFormat") != metadataDict.end()) { pixelFormatName = metadataDict.at("pixelFormat").asString(); } } Texture2D *texture = nullptr; static std::unordered_map<std::string, Texture2D::PixelFormat> pixelFormats = { {"RGBA8888", Texture2D::PixelFormat::RGBA8888}, {"RGBA4444", Texture2D::PixelFormat::RGBA4444}, {"RGB5A1", Texture2D::PixelFormat::RGB5A1}, {"RGBA5551", Texture2D::PixelFormat::RGB5A1}, {"RGB565", Texture2D::PixelFormat::RGB565}, {"A8", Texture2D::PixelFormat::A8}, {"ALPHA", Texture2D::PixelFormat::A8}, {"I8", Texture2D::PixelFormat::I8}, {"AI88", Texture2D::PixelFormat::AI88}, {"ALPHA_INTENSITY", Texture2D::PixelFormat::AI88}, //{"BGRA8888", Texture2D::PixelFormat::BGRA8888}, no Image conversion RGBA -> BGRA {"RGB888", Texture2D::PixelFormat::RGB888} }; auto pixelFormatIt = pixelFormats.find(pixelFormatName); if (pixelFormatIt != pixelFormats.end()) { const Texture2D::PixelFormat pixelFormat = (*pixelFormatIt).second; const Texture2D::PixelFormat currentPixelFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::setDefaultAlphaPixelFormat(pixelFormat); texture = Director::getInstance()->getTextureCache()->addImage(texturePath); Texture2D::setDefaultAlphaPixelFormat(currentPixelFormat); } else { texture = Director::getInstance()->getTextureCache()->addImage(texturePath); } if (texture) { addSpriteFramesWithDictionary(dict, texture); } else { CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture"); } }
//添加角色 void TollgateScene::addPlayer(TMXTiledMap* map) { // Size visibleSize = Director::getInstance()->getVisibleSize(); //创建精灵 Sprite* playerSprite = Sprite::create("player.png"); //讲精灵绑定到对象 Player* mPlayer = Player::create(); mPlayer->BindSprite(playerSprite); mPlayer->run(); //加载对象层 TMXObjectGroup* objGroup = map->getObjectGroup("objects"); //加载玩家对象坐标 ValueMap playerPointMap = objGroup->getObject("PlayerPoint"); float playerX = playerPointMap.at("x").asFloat(); float PlayerY = playerPointMap.at("y").asFloat(); //设置玩家坐标 mPlayer->setPosition(Point(playerX,PlayerY)); //将玩家添加到地图 map->addChild(mPlayer); //创建简单的玩家控制器 SimpleMoveController* simpleMoveControll = SimpleMoveController::create(); //设置速度 simpleMoveControll->setiSpeed(1); this->addChild(simpleMoveControll); mPlayer->setController(simpleMoveControll); }
void GameMap::onMapLoadCompleted(){ auto map = this->_map; if (map == NULL){ log("error: map is null"); return; } ValueMap properties = map->getProperties(); if (properties == ValueMapNull){ return; } int triggerPlotId = properties.at("triggerPlotId").asInt(); if (triggerPlotId != 0 && dialogueManager != NULL){ //触发对话事件 triggerPlot(triggerPlotId); } }
void PlayLayer::initPointsVector(float offX) { Node *runOfPoint = NULL; int count = 0; ValueMap point; point = objects->getObject(std::to_string(count)); while (point.begin()!= point.end()) { float x = point.at("x").asFloat(); float y = point.at("y").asFloat(); runOfPoint = Node::create(); runOfPoint->setPosition(Point(x - offX , y )); this->pointsVector.pushBack(runOfPoint); count++; point = objects->getObject( std::to_string(count)); } runOfPoint = NULL; }
bool StartScene::canBuildOnTilePosition(Point pos) { Point towerLoc = this->tileCoordForPosition(pos); int tileGid = this->_background->getTileGIDAt(towerLoc); Value props = this->_tileMap->getPropertiesForGID(tileGid); ValueMap map = props.asValueMap(); int type_int; if (map.size() == 0) { type_int = 0; } else { type_int = map.at("buildable").asInt(); } if (1 == type_int) { return true; } return false; }
void StartScene::addWayPoint() { DataModel *m = DataModel::getModel(); auto objects = this->_tileMap->objectGroupNamed("Objects"); WayPoint *wp = NULL; std::string stringWithFormat = "Waypoint"; int wayPointCounter = 0; ValueMap wayPoint; wayPoint = objects->objectNamed(stringWithFormat + to_string(wayPointCounter)); while (wayPoint.begin() != wayPoint.end()) { int x = wayPoint.at("x").asInt(); int y = wayPoint.at("y").asInt(); wp = WayPoint::create(); wp->setPosition(ccp(x, y)); m->waypoints.pushBack(wp); wayPointCounter++; wayPoint = objects->objectNamed(stringWithFormat + to_string(wayPointCounter)); } wp =NULL; }
bool CollectObject::init(int id, Point position) { if (!GameObject::init(id, position)) { return false; } ValueMap *data = DataManager::getInstance()->getItemByID(id); _spriteMain = Sprite::create(data->at("itemImage").asString()); _spriteMain->setPosition(position); this->addChild(_spriteMain); auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [this](Touch* touch, Event* event) { auto target = static_cast<Sprite *>(event->getCurrentTarget()); Point locationInNode = target->convertToNodeSpace(touch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); if (rect.containsPoint(locationInNode)) { if(checkDistance(_spriteMain->getPosition())) { action(); } return true; } return false; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, _spriteMain); return true; }
Vec2 Game::randomMovePosition(SpriteBase* monster){ Point position; int randX = CCRANDOM_0_1()*199; int randY = CCRANDOM_0_1()*99; if(monster->getMoveCount() % 2 == 0){ position = Vec2(monster->getPosition().x + randX, monster->getPosition().y + randY); if(!monster->isFlippedX()){ monster->setFlippedX(true); } }else{ position = Vec2(monster->getPosition().x - randX, monster->getPosition().y - randY); if(!monster->isFlippedX()){ monster->setFlippedX(false); } } Vec2 tileCoord = tileCoordForPosition(position); if(tileCoord.x < 0 || tileCoord.x >= tileMap->getMapSize().width || tileCoord.y < 0 || tileCoord.y >= tileMap->getMapSize().height){ return randomMovePosition(monster); } int tileGid = collidable->getTileGIDAt(tileCoord); // 如果随机坐标是不可通过的网格位置,则重新获取 if (tileGid) { // 使用GID来查找指定tile的属性,返回一个Value Value properties = tileMap->getPropertiesForGID(tileGid); // 返回的Value实际是一个ValueMap ValueMap map = properties.asValueMap(); // 查找ValueMap,判断是否有”可碰撞的“物体,如果有,设置网格对象的isPass变量为false std::string value = map.at("collidable").asString(); if (value.compare("true") == 0) { return randomMovePosition(monster); }else{ return position; } } // 如果坐标正常直接返回 return position; }
void CSprite::bind(const string& pattern, float duration) { vector<string> values = CStringUtil::split(pattern, BIND_DELIMITER); if (values.size() != 2) { assert(NULL); } string plistFile = values[0]; string identifier = values[1]; ValueMap* dict = SpecialResource::getInstance()->getInfoPlist(); ValueMap frames = dict->at(BIND_PLIST_FRAMES_NODE).asValueMap(); int foundTotal = 0; for (auto& frame : frames) { string prefix = frame.first.substr(0, frame.first.find_last_of(BIND_PATTERN_CONNECTOR)); if (prefix == identifier) { foundTotal++; } } if (foundTotal == 0) { assert(NULL); } if (duration == -1) { duration = BIND_DEFAULT_DURATION_PER_FRAME * foundTotal; } string frameNamePattern = identifier + BIND_PATTERN_SUFFIX; string nameNotLoop = identifier + BIND_NOT_LOOP; string nameLoop = identifier + BIND_LOOP; Action* notLoopAction = createFrameCaheAction(frameNamePattern, foundTotal, duration, false); retainAction(notLoopAction, nameNotLoop); Action* loopAction = createFrameCaheAction(frameNamePattern, foundTotal, duration, true); retainAction(loopAction, nameLoop); this->lastActionName = identifier; }
void StartScene::addTower(Point pos, Tower::TowerType towerType) { DataModel *m = DataModel::getModel(); Tower *target = NULL ; Point towerLoc = this->tileCoordForPosition(pos); int tileGid = this->_background->tileGIDAt(towerLoc); Value props = this->_tileMap->propertiesForGID(tileGid); ValueMap map = props.asValueMap(); int type_int = map.at("buildable").asInt(); target = Tower::createWithType(towerType); if (target->price>m->currentMoney) { MessageBox("no enough money!",""); return; } if (1 == type_int) { // std::string targetPos = "pos.x = "+std::to_string(towerLoc.x)+" pos.y = "+std::to_string(towerLoc.y); // log(targetPos.c_str()); bool buildable = true; for (auto point = m->buildedPoints.equal_range(towerLoc.x); point.first!=point.second; ++point.first) { if (towerLoc.y==point.first->second) { buildable = false; break; } } if (buildable) { m->buildedPoints.insert(std::make_pair(towerLoc.x, towerLoc.y)); target->setPosition(ccp((towerLoc.x * 32) + 16, this->_tileMap->getContentSize().height - (towerLoc.y * 32) - 16)); this->addChild(target,1); target->setTag(1); m->currentMoney -= target->price; money->setText(to_string(m->currentMoney)); m->towers.pushBack(target); } } else { log("Tile Not Buildable"); } }
bool PEShapeCache::removeBodysWithFile(const std::string &plist) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(plist); CCASSERT(!dict.empty(), "Shape-file not found"); CCASSERT(dict.size() != 0, "plist file empty or not existing"); ValueMap &metadata = dict["metadata"].asValueMap(); int format = metadata["format"].asInt(); CCASSERT(format == 1, "format not supported!"); ValueMap &bodydict = dict.at("bodies").asValueMap(); for (auto iter = bodydict.cbegin(); iter != bodydict.cend(); ++iter) { std::string bodyName = iter->first; BodyDef *bd = bodyDefs.at(bodyName); if (bd != nullptr) { safeReleaseBodyDef(bd); bodyDefs.erase(bodyName); } } return true; }
void UserDataMgr::loadFromDisk() { string fpath = FileUtils::getInstance()->getWritablePath(); ValueMap data = FileUtils::getInstance()->getValueMapFromFile(fpath+"user.txt"); if (data.empty()) { for (int i=udi_heart; i<udi_count; ++i) { m_val[i] = 0; } } else { for (int i=udi_heart; i<udi_count; ++i) { m_val[i] = data.at( to_string(i) ).asInt(); } } if (m_val[0] == 0) m_val[0] = 1; }