TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const { CCASSERT(groupName.size() > 0, "Invalid group name!"); if (_objectGroups.size()>0) { TMXObjectGroup* objectGroup = nullptr; for (auto iter = _objectGroups.cbegin(); iter != _objectGroups.cend(); ++iter) { objectGroup = *iter; if (objectGroup && objectGroup->getGroupName() == groupName) { return objectGroup; } } } // objectGroup not found return nullptr; }
bool GameScene::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); if(NULL==map){ map=TMXTiledMap::create("map/map1.tmx"); } //map->setScale(2); addChild(map); TMXObjectGroup *objects = map->getObjectGroup("player"); CCASSERT(NULL != objects, "'Objects' object group not found"); auto spawnPoint = objects->getObject("playerinit"); CCASSERT(!spawnPoint.empty(), "SpawnPoint object not found"); int x = spawnPoint["x"].asInt(); int y = spawnPoint["y"].asInt(); Player * player = new Player(); global->player=player; global->map=map; player->setPosition(Vec2(x,y)); addChild(player,2); //player->sprite->runAction(RepeatForever::create(Animate::create(global->createAni(player->texture, 3)))); TMXObjectGroup *object2=map->getObjectGroup("Event"); auto transitionpoint=object2->getObject("transitionEvent"); int x1=transitionpoint["x"].asInt(); int y1=transitionpoint["y"].asInt(); transitionPosition=Vec2(x1,y1); //CCLOG("over"); this->runAction(CCFollow::create(player,CCRectMake(0,0,map->getContentSize().width,map->getContentSize().height))); schedule(schedule_selector(GameScene::updateEvent), 0.1); return true; }
// the XML parser calls here with all the elements void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { CC_UNUSED_PARAM(ctx); TMXMapInfo *tmxMapInfo = this; std::string elementName = name; ValueMap attributeDict; if (atts && atts[0]) { for (int i = 0; atts[i]; i += 2) { std::string key = atts[i]; std::string value = atts[i+1]; attributeDict.insert(std::make_pair(key, Value(value))); } } if (elementName == "map") { std::string version = attributeDict["version"].asString(); if ( version != "1.0") { CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %s", version.c_str()); } std::string orientationStr = attributeDict["orientation"].asString(); if (orientationStr == "orthogonal") { tmxMapInfo->setOrientation(TMXOrientationOrtho); } else if (orientationStr == "isometric") { tmxMapInfo->setOrientation(TMXOrientationIso); } else if (orientationStr == "hexagonal") { tmxMapInfo->setOrientation(TMXOrientationHex); } else if (orientationStr == "staggered") { tmxMapInfo->setOrientation(TMXOrientationStaggered); } else { CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", tmxMapInfo->getOrientation()); } Size s; s.width = attributeDict["width"].asFloat(); s.height = attributeDict["height"].asFloat(); tmxMapInfo->setMapSize(s); s.width = attributeDict["tilewidth"].asFloat(); s.height = attributeDict["tileheight"].asFloat(); tmxMapInfo->setTileSize(s); // The parent element is now "map" tmxMapInfo->setParentElement(TMXPropertyMap); } else if (elementName == "tileset") { // If this is an external tileset then start parsing that std::string externalTilesetFilename = attributeDict["source"].asString(); if (externalTilesetFilename != "") { _externalTilesetFilename = externalTilesetFilename; // Tileset file will be relative to the map file. So we need to convert it to an absolute path if (_TMXFileName.find_last_of("/") != string::npos) { string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1); externalTilesetFilename = dir + externalTilesetFilename; } else { externalTilesetFilename = _resources + "/" + externalTilesetFilename; } externalTilesetFilename = FileUtils::getInstance()->fullPathForFilename(externalTilesetFilename); _currentFirstGID = attributeDict["firstgid"].asInt(); if (_currentFirstGID < 0) { _currentFirstGID = 0; } _recordFirstGID = false; tmxMapInfo->parseXMLFile(externalTilesetFilename); } else { TMXTilesetInfo *tileset = new (std::nothrow) TMXTilesetInfo(); tileset->_name = attributeDict["name"].asString(); if (_recordFirstGID) { // unset before, so this is tmx file. tileset->_firstGid = attributeDict["firstgid"].asInt(); if (tileset->_firstGid < 0) { tileset->_firstGid = 0; } } else { tileset->_firstGid = _currentFirstGID; _currentFirstGID = 0; } tileset->_spacing = attributeDict["spacing"].asInt(); tileset->_margin = attributeDict["margin"].asInt(); Size s; s.width = attributeDict["tilewidth"].asFloat(); s.height = attributeDict["tileheight"].asFloat(); tileset->_tileSize = s; tmxMapInfo->getTilesets().pushBack(tileset); tileset->release(); } } else if (elementName == "tile") { if (tmxMapInfo->getParentElement() == TMXPropertyLayer) { TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Size layerSize = layer->_layerSize; uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asInt()); int tilesAmount = layerSize.width*layerSize.height; if (_xmlTileIndex < tilesAmount) { layer->_tiles[_xmlTileIndex++] = gid; } } else { TMXTilesetInfo* info = tmxMapInfo->getTilesets().back(); tmxMapInfo->setParentGID(info->_firstGid + attributeDict["id"].asInt()); tmxMapInfo->getTileProperties()[tmxMapInfo->getParentGID()] = Value(ValueMap()); tmxMapInfo->setParentElement(TMXPropertyTile); } } else if (elementName == "layer") { TMXLayerInfo *layer = new (std::nothrow) TMXLayerInfo(); layer->_name = attributeDict["name"].asString(); Size s; s.width = attributeDict["width"].asFloat(); s.height = attributeDict["height"].asFloat(); layer->_layerSize = s; Value& visibleValue = attributeDict["visible"]; layer->_visible = visibleValue.isNull() ? true : visibleValue.asBool(); Value& opacityValue = attributeDict["opacity"]; layer->_opacity = opacityValue.isNull() ? 255 : (unsigned char)(255.0f * opacityValue.asFloat()); float x = attributeDict["x"].asFloat(); float y = attributeDict["y"].asFloat(); layer->_offset.set(x, y); tmxMapInfo->getLayers().pushBack(layer); layer->release(); // The parent element is now "layer" tmxMapInfo->setParentElement(TMXPropertyLayer); } else if (elementName == "objectgroup") { TMXObjectGroup *objectGroup = new (std::nothrow) TMXObjectGroup(); objectGroup->setGroupName(attributeDict["name"].asString()); Vec2 positionOffset; positionOffset.x = attributeDict["x"].asFloat() * tmxMapInfo->getTileSize().width; positionOffset.y = attributeDict["y"].asFloat() * tmxMapInfo->getTileSize().height; objectGroup->setPositionOffset(positionOffset); tmxMapInfo->getObjectGroups().pushBack(objectGroup); objectGroup->release(); // The parent element is now "objectgroup" tmxMapInfo->setParentElement(TMXPropertyObjectGroup); } else if (elementName == "image") { TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back(); // build full path std::string imagename = attributeDict["source"].asString(); tileset->_originSourceImage = imagename; if (_TMXFileName.find_last_of("/") != string::npos) { string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1); tileset->_sourceImage = dir + imagename; } else { tileset->_sourceImage = _resources + (_resources.size() ? "/" : "") + imagename; } } else if (elementName == "data") { std::string encoding = attributeDict["encoding"].asString(); std::string compression = attributeDict["compression"].asString(); if (encoding == "") { tmxMapInfo->setLayerAttribs(tmxMapInfo->getLayerAttribs() | TMXLayerAttribNone); TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Size layerSize = layer->_layerSize; int tilesAmount = layerSize.width*layerSize.height; uint32_t *tiles = (uint32_t*) malloc(tilesAmount*sizeof(uint32_t)); // set all value to 0 memset(tiles, 0, tilesAmount*sizeof(int)); layer->_tiles = tiles; } else if (encoding == "base64") { int layerAttribs = tmxMapInfo->getLayerAttribs(); tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64); tmxMapInfo->setStoringCharacters(true); if (compression == "gzip") { layerAttribs = tmxMapInfo->getLayerAttribs(); tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip); } else if (compression == "zlib") { layerAttribs = tmxMapInfo->getLayerAttribs(); tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib); } CCASSERT( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" ); } } else if (elementName == "object") { TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back(); // The value for "type" was blank or not a valid class name // Create an instance of TMXObjectInfo to store the object and its properties ValueMap dict; // Parse everything automatically const char* keys[] = {"name", "type", "width", "height", "gid"}; for (const auto& key : keys) { Value value = attributeDict[key]; dict[key] = value; } // But X and Y since they need special treatment // X int x = attributeDict["x"].asInt(); // Y int y = attributeDict["y"].asInt(); Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().y - attributeDict["height"].asInt()); p = CC_POINT_PIXELS_TO_POINTS(p); dict["x"] = Value(p.x); dict["y"] = Value(p.y); int width = attributeDict["width"].asInt(); int height = attributeDict["height"].asInt(); Size s(width, height); s = CC_SIZE_PIXELS_TO_POINTS(s); dict["width"] = Value(s.width); dict["height"] = Value(s.height); // Add the object to the objectGroup objectGroup->getObjects().push_back(Value(dict)); // The parent element is now "object" tmxMapInfo->setParentElement(TMXPropertyObject); } else if (elementName == "property") { if ( tmxMapInfo->getParentElement() == TMXPropertyNone ) { CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'", attributeDict["name"].asString().c_str(), attributeDict["value"].asString().c_str() ); } else if ( tmxMapInfo->getParentElement() == TMXPropertyMap ) { // The parent element is the map Value value = attributeDict["value"]; std::string key = attributeDict["name"].asString(); tmxMapInfo->getProperties().insert(std::make_pair(key, value)); } else if ( tmxMapInfo->getParentElement() == TMXPropertyLayer ) { // The parent element is the last layer TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Value value = attributeDict["value"]; std::string key = attributeDict["name"].asString(); // Add the property to the layer layer->getProperties().insert(std::make_pair(key, value)); } else if ( tmxMapInfo->getParentElement() == TMXPropertyObjectGroup ) { // The parent element is the last object group TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back(); Value value = attributeDict["value"]; std::string key = attributeDict["name"].asString(); objectGroup->getProperties().insert(std::make_pair(key, value)); } else if ( tmxMapInfo->getParentElement() == TMXPropertyObject ) { // The parent element is the last object TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); std::string propertyName = attributeDict["name"].asString(); dict[propertyName] = attributeDict["value"]; } else if ( tmxMapInfo->getParentElement() == TMXPropertyTile ) { ValueMap& dict = tmxMapInfo->getTileProperties().at(tmxMapInfo->getParentGID()).asValueMap(); std::string propertyName = attributeDict["name"].asString(); dict[propertyName] = attributeDict["value"]; } } else if (elementName == "polygon") { // find parent object's dict and add polygon-points to it TMXObjectGroup* objectGroup = _objectGroups.back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); // get points value string std::string value = attributeDict["points"].asString(); if (!value.empty()) { ValueVector pointsArray; pointsArray.reserve(10); // parse points string into a space-separated set of points stringstream pointsStream(value); string pointPair; while (std::getline(pointsStream, pointPair, ' ')) { // parse each point combo into a comma-separated x,y point stringstream pointStream(pointPair); string xStr, yStr; ValueMap pointDict; // set x if (std::getline(pointStream, xStr, ',')) { int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x; pointDict["x"] = Value(x); } // set y if (std::getline(pointStream, yStr, ',')) { int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y; pointDict["y"] = Value(y); } // add to points array pointsArray.push_back(Value(pointDict)); } dict["points"] = Value(pointsArray); } } else if (elementName == "polyline") { // find parent object's dict and add polyline-points to it TMXObjectGroup* objectGroup = _objectGroups.back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); // get points value string std::string value = attributeDict["points"].asString(); if (!value.empty()) { ValueVector pointsArray; pointsArray.reserve(10); // parse points string into a space-separated set of points stringstream pointsStream(value); string pointPair; while (std::getline(pointsStream, pointPair, ' ')) { // parse each point combo into a comma-separated x,y point stringstream pointStream(pointPair); string xStr, yStr; ValueMap pointDict; // set x if (std::getline(pointStream, xStr, ',')) { int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x; pointDict["x"] = Value(x); } // set y if (std::getline(pointStream, yStr, ',')) { int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y; pointDict["y"] = Value(y); } // add to points array pointsArray.push_back(Value(pointDict)); } dict["polylinePoints"] = Value(pointsArray); } } }
// on "init" you need to initialize your instance bool GameWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } instance = this; scoreManager = new ScoreManager(); npcManager = new NpcManager(); structureManager = new StructureManager(); touchLocation = ccp(-1, -1); auto rootNode = CSLoader::createNode("MainScene.csb"); addChild(rootNode); _tileMap = TMXTiledMap::create("greenmap.tmx"); pathFinding = new PathFinding(); _background = _tileMap->layerNamed("Background"); TMXObjectGroup *objectGroup = _tileMap->objectGroupNamed("Objects"); if (objectGroup == NULL){ return false; } auto spawnPoints = objectGroup->objectNamed("spawnPoint"); int x = spawnPoints.at("x").asInt(); int y = spawnPoints.at("y").asInt(); this->addChild(_tileMap); player = new Player(ccp(x, y)); _meta = _tileMap->layerNamed("Meta"); _meta->setVisible(false); CCPoint cp1 = tileCoordForPosition(ccp(798, 444)); CCPoint cp2 = tileCoordToPosition(cp1); //CCLOG("x: %f, y: %f", cp2.x, cp2.y); this->addChild(player->entityImage, 2); this->setViewPointCenter(player->entityImage->getPosition()); heartsprite = new cocos2d::Sprite(); heartsprite->initWithFile("heart.png"); heartsprite->setScale(1.5f, 1.5f); heartsprite->setPosition(this->convertToNodeSpace(CCDirector::sharedDirector()->convertToGL(ccp(30, 60)))); this->addChild(heartsprite, 3); healthLabel = Label::createWithTTF(std::to_string(player->currentHealth), "kenney-rocket.ttf", 32); healthLabel->setColor(cocos2d::Color3B::RED); healthLabel->enableOutline(Color4B(0,0,0,255),3); healthLabel->setPosition(this->convertToNodeSpace(CCDirector::sharedDirector()->convertToGL(ccp(114, 60)))); this->addChild(healthLabel, 3); scoreTextLabel = Label::createWithTTF("Score:", "kenney-rocket.ttf", 24); scoreTextLabel->enableOutline(Color4B(0,0,0,255),3); scoreTextLabel->setPosition(this->convertToNodeSpace(CCDirector::sharedDirector()->convertToGL(ccp(100, 100)))); this->addChild(scoreTextLabel, 3); scoreLabel = Label::createWithTTF(std::to_string(scoreManager->getScore()), "kenney-rocket.ttf", 32); scoreLabel->enableOutline(Color4B(0,0,0,255),4); pointlocation = this->convertToNodeSpace(CCDirector::sharedDirector()->convertToGL(ccp(110, 130))); scoreLabel->setPosition(pointlocation); this->addChild(scoreLabel, 3); keyboardListener(); this->scheduleUpdate(); this->schedule(schedule_selector(GameWorld::cameraUpdater), 1.0f); 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; }
void DebugMap::parseMap( cocos2d::TMXTiledMap* tmap ){ TMXObjectGroup* wall = tmap->getObjectGroup("linewall"); Size mapSize = tmap->getContentSize(); tilesLen = tmap->getMapSize(); tilesSize= tmap->getTileSize()/2; CCLOG("parseMap %f %f", D::mapSize.width, D::mapSize.height ); for( int i=0; i<tilesLen.height+1; i++ ) this->drawLine( Vec2( 0, i*(tilesSize.height)), Vec2( mapSize.width, i*(tilesSize.height) ), Color4F::BLUE ); for( int j=0; j<tilesLen.width+1; j++ ) this->drawLine( Vec2( j*(tilesSize.width), 0 ), Vec2( j*(tilesSize.width), mapSize.height ), Color4F::BLUE ); // CCLOG(" Line... %f, %f", tmap->getMapSize().width, tmap->getMapSize().height ); // 갯수 // CCLOG(" Line... %f, %f", tmap->getTileSize().width, tmap->getTileSize().height ); // 크기 DrawNode* wallNode = DrawNode::create(); this->addChild( wallNode ); int lineCount = 0; for( auto obj : wall->getObjects()) { bool first = true; Vec2 prevPoint; auto xx = obj.asValueMap()["x"].asFloat(); auto yy = obj.asValueMap()["y"].asFloat(); // 벽 생성 및 위치 for( auto value : obj.asValueMap() ) { if( value.first == "polylinePoints"){ wallSeg.push_back( *new std::vector<Vec2> ); auto vec = value.second.asValueVector(); CCLOG("catch Line %d", lineCount ); first = true; for( auto &p : vec ){ Vec2 point = Vec2( ( p.asValueMap().at("x").asFloat()*.5 ) + xx, -( p.asValueMap().at("y").asFloat()*.5 ) + yy ); if( first == false ){ wallNode->drawSegment( prevPoint, point, 3.0f, Color4F::WHITE ); } wallSeg[lineCount].push_back(point); prevPoint = point; first = false; }//for CCLOG( "(%d) line length is %lu", lineCount, wallSeg[lineCount].size()); lineCount += 1; }//if }//for } parentMap.reserve(100); getFastDistance( 8,0, 6,8 ); }
bool HelloWorld::init() { if ( !CCLayer::init() ) { return false; } _tileMap = TMXTiledMap::create("ai_map.tmx"); //_tileMap->initWithTMXFile("ai_map.tmx"); _background = _tileMap->getLayer("Background"); _foreground_1 = _tileMap->getLayer("Foreground_1"); _foreground_2 = _tileMap->getLayer("Foreground_2"); _meta = _tileMap->getLayer("Meta"); _meta->setVisible(false); this->addChild(_tileMap); TMXObjectGroup *objectGroup = _tileMap->getObjectGroup("Objects"); CCASSERT(NULL != objectGroup, "SpawnPoint object not found"); auto spawnPoint = objectGroup->getObject("SpawnPoint"); CCASSERT(!spawnPoint.empty(), "SpawnPoint object not found"); //CCDictionary *spawnPoint = objectGroup->objectNamed("SpawnPoint"); //int x = ((CCString)spawnPoint.valueForKey("x")).intValue(); //int y = ((CCString)spawnPoint.valueForKey("y")).intValue(); int x = spawnPoint["x"].asInt(); int y = spawnPoint["y"].asInt(); // player _player = Sprite::create("egg.png"); _player->setTag(5); _player->setPosition(x,y); addChild(_player); setViewPointCenter(_player->getPosition()); // patrol enemy searching_enemy = Enemys::createWithLayer(this); searching_enemy->setGameLayer(this); auto enemy = objectGroup->getObject("EnemySpawn1"); int x_1 = enemy["x"].asInt(); int y_1 = enemy["y"].asInt(); addEnemyAtPos(Point(x_1,y_1)); _enemies.pushBack(searching_enemy); // archer archer = Sprite::create("Kiwi.png"); archer->setPosition(positionForTileCoord(Point(12, 4))); archer->setTag(23); archer->setScale(1.0); this->addChild(archer,1); _enemies.pushBack(archer); //boss boss = Sprite::create("patrol.png"); boss->setPosition(positionForTileCoord(Point(26,9))); boss->setTag(26); boss->setScale(1.7); this->addChild(boss); _enemies.pushBack(boss); //a princess princess = Sprite::create("Princess.png"); princess->setPosition(positionForTileCoord(Point(28, 10))); princess->setScale(0.6); this->addChild(princess); auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [&](Touch* touch, Event* unused_event)->bool { return true; }; listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this); this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // a pause button auto pauseItem = MenuItemImage::create("pause.png","",CC_CALLBACK_1(HelloWorld::onPause, this)); auto menu = Menu::create(pauseItem,NULL); pauseItem->setScale(0.2); pauseItem->setPosition(positionForTileCoord(Point(27, 1))); menu->setPosition(Point::ZERO); this->addChild(menu,1,5); // add background music //CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("SummerNight.wav"); // navigation button:up, down, left and right and an attacking button auto left_btn = Sprite::create("left.png"); left_btn->setScale(0.3); left_btn->setPosition(Point(100, 125)); left_btn->setTag(TAG_LEFT); this->addChild(left_btn,1); auto right_btn = Sprite::create("right.png"); right_btn->setScale(0.3); right_btn->setPosition(Point(250, 125)); right_btn->setTag(TAG_RIGHT); this->addChild(right_btn,1); auto up_btn = Sprite::create("up.png"); up_btn->setScale(0.3); up_btn->setPosition(Point(175, 200)); up_btn->setTag(TAG_UP); this->addChild(up_btn,1); auto down_btn = Sprite::create("down.png"); down_btn->setScale(0.3); down_btn->setPosition(Point(175, 50)); down_btn->setTag(TAG_DOWN); this->addChild(down_btn,1); auto attack_btn = Sprite::create("attack.png"); attack_btn->setScale(0.5); attack_btn->setPosition(positionForTileCoord(Point(25,16))); attack_btn->setTag(ATTACK); this->addChild(attack_btn,1); //hero hp Sprite *heroEmHP = Sprite::create("empty.png"); heroEmHP->setPosition(Point(150, 600)); heroEmHP->setScale(1.5); this->addChild(heroEmHP); Sprite* heroFuHP = Sprite::create("full.png"); ProgressTimer *pBlood = ProgressTimer::create(heroFuHP); pBlood->setType(kCCProgressTimerTypeBar); pBlood->setMidpoint(Point(0, 0)); pBlood->setBarChangeRate(Point(1, 0)); pBlood->setPercentage(100.0f); pBlood->setPosition(Point(150, 600)); pBlood->setScale(1.5); this->addChild(pBlood, 1, 6); auto hero =Sprite::create("hero.png"); hero->setPosition(Point(50, 600)); hero->setScale(0.3); this->addChild(hero); //patrol monster hp Sprite *enEmHP = Sprite::create("empty.png"); enEmHP->setPosition(Point(150, 550)); enEmHP->setScale(1.5); this->addChild(enEmHP,1,7); Sprite* enFuHP = Sprite::create("full.png"); ProgressTimer *enpBlood = ProgressTimer::create(enFuHP); enpBlood->setType(kCCProgressTimerTypeBar); enpBlood->setMidpoint(Point(0, 0)); enpBlood->setBarChangeRate(Point(1, 0)); enpBlood->setPercentage(100.0f); enpBlood->setPosition(Point(150, 550)); enpBlood->setScale(1.5); this->addChild(enpBlood, 1,8); auto monster = Sprite::create("monster.png"); monster->setPosition(Point(50,550)); monster->setScale(0.1); monster->setTag(9); this->addChild(monster); //archer Sprite *arEmHP = Sprite::create("empty.png"); arEmHP->setPosition(Point(350, 600)); arEmHP->setScale(1.5); this->addChild(arEmHP,1,10); Sprite* arFuHP = Sprite::create("full.png"); ProgressTimer *arpBlood = ProgressTimer::create(arFuHP); arpBlood->setType(kCCProgressTimerTypeBar); arpBlood->setMidpoint(Point(0, 0)); arpBlood->setBarChangeRate(Point(1, 0)); arpBlood->setPercentage(100.0f); arpBlood->setPosition(Point(350, 600)); arpBlood->setScale(1.5); this->addChild(arpBlood, 1,11); auto armonster = Sprite::create("archer_icon.png"); armonster->setPosition(Point(250,600)); armonster->setScale(0.1); armonster->setTag(12); this->addChild(armonster); //boss Sprite *boEmHP = Sprite::create("empty.png"); boEmHP->setPosition(Point(350, 550)); boEmHP->setScale(1.5); this->addChild(boEmHP,1,13); Sprite* boFuHP = Sprite::create("full.png"); ProgressTimer *bopBlood = ProgressTimer::create(boFuHP); bopBlood->setType(kCCProgressTimerTypeBar); bopBlood->setMidpoint(Point(0, 0)); bopBlood->setBarChangeRate(Point(1, 0)); bopBlood->setPercentage(100.0f); bopBlood->setPosition(Point(350, 550)); bopBlood->setScale(1.5); this->addChild(bopBlood, 1,14); auto bomonster = Sprite::create("boss_icon.png"); bomonster->setPosition(Point(250,550)); bomonster->setScale(0.2); bomonster->setTag(15); this->addChild(bomonster); this->schedule(schedule_selector(HelloWorld::shooting), 2.5f); this->schedule(schedule_selector(HelloWorld::bulletCollision)); this->schedule(schedule_selector(HelloWorld::getPrincess)); this->schedule(schedule_selector(HelloWorld::bossAttacking),1.0f); return true; }
void GameMap::initActor() { TMXObjectGroup* group = this->objectGroupNamed("actor"); const ValueVector &objects = group->getObjects(); for (ValueVector::const_iterator it=objects.begin(); it!=objects.end(); it++) { const ValueMap &dict = (*it).asValueMap(); int x = dict.at("x").asInt(); int y = dict.at("y").asInt(); Vec2 pos = Vec2(x, y); std::string texture = dict.at("texture").asString(); CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(texture+".plist"); if (dict.at("enemy").asInt() == 0){ auto actor = ActorSprite::MyCreateInit(texture); //初始化属性值 actor->atk = dict.at("atk").asInt(); actor->Tag = dict.at("tag").asInt(); actor->life = dict.at("life").asInt(); actor->range = dict.at("range").asInt(); //增加了属性 actor->atkrange = dict.at("atkrange").asInt(); // auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(ActorSprite::onTouchBegan, actor); listener->onTouchEnded = CC_CALLBACK_2(ActorSprite::onTouchEnded, actor); listener->setSwallowTouches(true); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, actor); //-----------------------改了,添加监听 actor->setPosition(pos+_tileSize/2); addChild(actor, 4); //增加血条 Sprite* bloodsp = Sprite::create("blood.png"); bloodsp->setScaleX(actor->life); bloodsp->setPosition(Vec2(actor->getContentSize().width/2, actor->getContentSize().height)); actor->addChild(bloodsp); bloodsp->setTag(actor->Tag); //增加血条 //把人物存放到容器中 friendArray.pushBack(actor); actor->setName(actor->ActorName); }else{ auto actor = EnemySprite::MyCreateInit(texture); actor->setOpacity(100); //初始化属性值 actor->atk = dict.at("atk").asInt(); actor->Tag = dict.at("tag").asInt(); actor->life = dict.at("life").asInt(); actor->range = dict.at("range").asInt(); actor->atkrange = dict.at("atkrange").asInt(); // auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(EnemySprite::onTouchBegan, actor); listener->onTouchEnded = CC_CALLBACK_2(EnemySprite::onTouchEnded, actor); listener->setSwallowTouches(true); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, actor); //--------------------改了,添加监听 actor->setPosition(pos+_tileSize/2); addChild(actor, 4); Sprite* bloodsp = Sprite::create("blood.png"); bloodsp->setScaleX(actor->life); bloodsp->setPosition(Vec2(actor->getContentSize().width/2, actor->getContentSize().height)); actor->addChild(bloodsp); bloodsp->setTag(actor->Tag); //增加坏人存入vector中 enemyArray.pushBack(actor); actor->setName(actor->ActorName); } int width = dict.at("width").asInt(); int height = dict.at("height").asInt(); x /= width; y /= height; pos = Vec2(x, y); actorArray.insert(pos); } }
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); } }
void GameLayer::onEnter() { Layer::onEnter(); auto visibleSize = Director::getInstance()->getVisibleSize(); this->m_origin = Director::getInstance()->getVisibleOrigin(); m_pTiledMap = TMXTiledMap::create("TYCHEs_COFEE.tmx"); m_TiledMapSize.setSize(m_pTiledMap->getMapSize().width * m_pTiledMap->getTileSize().width, m_pTiledMap->getMapSize().height * m_pTiledMap->getTileSize().height); this->addChild(m_pTiledMap); TMXObjectGroup *objects = m_pTiledMap->getObjectGroup("Objects"); CCASSERT(NULL != objects, "'Objects' object group not found"); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("hero.plist"); auto spawnPoint = objects->getObject("SpawnPoint"); CCASSERT(!spawnPoint.empty(), "SpawnPoint object not found"); Point heroInitPos = m_origin + Point(spawnPoint["x"].asFloat(), spawnPoint["y"].asFloat()); m_pHero = Hero::create(); m_pHero->setScale(0.5f); m_pHero->setPosition(heroInitPos); m_pHero->runIdleAction(); m_pHero->setLocalZOrder(visibleSize.height - m_pHero->getPositionY()); m_pHero->setHP(100); m_pHero->setIsAttacking(false); m_pHero->setJumpStage(0); m_pHero->onDeadCallback = CC_CALLBACK_0(GameLayer::onHeroDead, this, m_pHero); m_pHero->attack = CC_CALLBACK_0(GameLayer::onHeroAttack, this); m_pHero->stop = CC_CALLBACK_0(GameLayer::onHeroStop, this); m_pHero->walk = CC_CALLBACK_1(GameLayer::onHeroWalk, this); m_pHero->jump = CC_CALLBACK_1(GameLayer::onHeroJump, this); this->addChild(m_pHero); auto centerOfView = Point(visibleSize.width / 2, visibleSize.height / 2); this->setPosition(centerOfView - m_pHero->getPosition()); m_pForesight = Foresight::create(); this->addChild(m_pForesight); JsonParser* parser = JsonParser::createWithFile("Debug.json"); parser->decodeDebugData(); auto list = parser->getList(); for (auto& v : list) { ValueMap row = v.asValueMap(); for (auto& pair : row) { CCLOG("%s %s", pair.first.c_str(), pair.second.asString().c_str()); if (pair.first.compare("HeroHSpeed") == 0) { float s = pair.second.asFloat(); m_pHero->setWalkVelocity(s); } else if (pair.first.compare("HeroVSpeed") == 0) { m_pHero->setJumpVelocity(pair.second.asFloat()); } else if (pair.first.compare("BulletPower") == 0) { m_pHero->setBullletPower(pair.second.asInt()); } else if (pair.first.compare("BulletSpeed") == 0) { m_pHero->setBulletLaunchVelocity(pair.second.asFloat()); } else if (pair.first.compare("BulletDisappearTime") == 0) { m_pHero->setBulletDisappearTime(pair.second.asFloat()); } else if (pair.first.compare("BulletAngle") == 0) { m_pHero->setBullletAngle(pair.second.asInt()); } else if (pair.first.compare("BulletInterval") == 0) { m_pHero->setBulletInterval(pair.second.asFloat()); } else if (pair.first.compare("WorldG") == 0) { //getScene()->getPhysicsWorld()->setGravity(Vec2(0.f, pair.second.asFloat())); } else if (pair.first.compare("ForesightSpeed") == 0) { initForesight(pair.second.asFloat()); } else if (pair.first.compare("AmmoCapacity") == 0) { m_pHero->setMaxAmmoCapacity(pair.second.asInt()); m_pHero->setAmmoCapacity(pair.second.asInt()); } } } /*const PhysicsMaterial m(1.f, 0.f, 0.f); Size boxSize(m_pTiledMap->getMapSize().width * m_pTiledMap->getTileSize().width, m_pTiledMap->getMapSize().height * m_pTiledMap->getTileSize().height); auto body = PhysicsBody::createEdgeBox(boxSize, m, 3); body->setTag(0); body->setCategoryBitmask(0x04); body->setContactTestBitmask(0x02); body->setCollisionBitmask(0x03); auto edgeNode = Node::create(); edgeNode->setPosition(Point(boxSize.width / 2, boxSize.height / 2)); edgeNode->setPhysicsBody(body); this->addChild(edgeNode);*/ importGroundData(m_pTiledMap); m_shootTime = m_pHero->getBulletInterval(); auto listener = EventListenerCustom::create("bullet_disappear", [this](EventCustom* event) { Bullet* bullet = static_cast<Bullet *>(event->getUserData()); if (bullet) this->removeChild(bullet); }); _eventDispatcher->addEventListenerWithFixedPriority(listener, 1); m_vecEventListener.pushBack(listener); /*auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = [this](PhysicsContact& contact)->bool { if (contact.getShapeA()->getBody()->getCategoryBitmask() == PC_Hero && contact.getShapeB()->getBody()->getCategoryBitmask() == PC_Ground) { Point posA = contact.getShapeA()->getBody()->getPosition(); Point posB = contact.getShapeB()->getBody()->getPosition(); if (posA.y >= posB.y) { Hero* hero = static_cast<Hero *>(contact.getShapeA()->getBody()->getNode()); if (hero->getCurrActionState() == ACTION_STATE_MOVE && hero->isInMoveAction(MOVE_STATE_DOWN)) { if (hero->isInMoveAction(MOVE_STATE_WALK)) { hero->stopMoveAction(MOVE_STATE_DOWN, true); Vec2 v = hero->getPhysicsBody()->getVelocity(); hero->walk(v.x); CCLOG("Hero Walk"); } else { CCLOG("Hero Stop"); hero->stop(); } hero->setJumpStage(0); } return true; } else { return false; } } else if (contact.getShapeA()->getBody()->getCategoryBitmask() == PC_Ground && contact.getShapeB()->getBody()->getCategoryBitmask() == PC_Hero) { Point posA = contact.getShapeA()->getBody()->getPosition(); Point posB = contact.getShapeB()->getBody()->getPosition(); if (posA.y <= posB.y) { Hero* hero = static_cast<Hero *>(contact.getShapeB()->getBody()->getNode()); if (hero->getCurrActionState() == ACTION_STATE_MOVE && hero->isInMoveAction(MOVE_STATE_DOWN)) { if (hero->isInMoveAction(MOVE_STATE_WALK)) { hero->stopMoveAction(MOVE_STATE_DOWN, true); Vec2 v = hero->getPhysicsBody()->getVelocity(); hero->walk(v.x); CCLOG("Hero Walk"); } else { CCLOG("Hero Stop"); hero->stop(); } hero->setJumpStage(0); } return true; } else { return false; } } else if(contact.getShapeA()->getBody()->getCategoryBitmask() == PC_Bullet && contact.getShapeB()->getBody()->getCategoryBitmask() == PC_Ground) { Bullet* bullet = static_cast<Bullet *>(contact.getShapeA()->getBody()->getNode()); if(bullet) { bullet->setIsActive(false); this->removeChild(bullet); } } else if(contact.getShapeA()->getBody()->getCategoryBitmask() == PC_Ground && contact.getShapeB()->getBody()->getCategoryBitmask() == PC_Bullet) { Bullet* bullet = static_cast<Bullet *>(contact.getShapeB()->getBody()->getNode()); if(bullet) { bullet->setIsActive(false); this->removeChild(bullet); } } return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); m_vecEventListener.pushBack(contactListener);*/ //this->getScene()->getPhysicsWorld()->setAutoStep(false); this->scheduleUpdate(); }
void PlayMapSix::onEnter() { Layer::onEnter(); bisover = false; //visibleSize,屏幕尺寸 visibleSize = Director::getInstance()->getVisibleSize(); //添加碰撞监听器 contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(PlayMapSix::onContactBegin, this); contactListener->onContactPostSolve = CC_CALLBACK_2(PlayMapSix::onContactPostSolve, this); contactListener->onContactPreSolve = CC_CALLBACK_2(PlayMapSix::onContactPreSolve, this); contactListener->onContactSeparate = CC_CALLBACK_1(PlayMapSix::onContactSeparate, this); //事件分发器 auto eventDispatcher = Director::getInstance()->getEventDispatcher(); eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); //网格地图 auto winSize = Director::getInstance()->getWinSize(); //map00瓦片地图地图 tilemap = TMXTiledMap::create("map/map6.tmx"); tilemap->setAnchorPoint(Vec2(0,0)); tilemap->setPosition(Vec2(0,0)); //auto group = tilemap->getObjectGroup("objects"); this->addChild(tilemap,-1); TMXObjectGroup *objects = tilemap->getObjectGroup("objLayer"); CCASSERT(NULL != objects, "'Objects' object group not found"); auto spawnPoint = objects->getObject("hero"); CCASSERT(!spawnPoint.empty(), "SpawnPoint object not found"); print_x = spawnPoint["x"].asInt(); print_y = spawnPoint["y"].asInt(); TMXLayer* layer = tilemap->getLayer("collideLayer");//从map中取出“bricks”图层 //这个循环嵌套是为了给每个砖块精灵设置一个刚体 int count = 0; for (int y = 0; y<TMX_HEIGHT; y++) { log("xxxxxxxxxxxxxxxxxxxx:%d", y); int groundcounter = 0; int deadlinecounter = 0; int dispearcounter = 0; int bodycounter = 0; Point groundpoint, deadlinepoint, dispearpoint, bodypoint; Size groundsize, deadlinesize, dispearsize, bodysize; for (int x = 0; x<TMX_WIDTH; x++) { int gid = layer->getTileGIDAt(Vec2(x, y)); Sprite* sprite = layer->getTileAt(Vec2(x, y));//从tile的坐标取出对应的精灵 if (gid == GROUND_GID) { log("sssssssssss %f,ppppppppppppp %f", sprite->getPosition().x, sprite->getPosition().y); if (groundcounter == 0) { groundpoint = Point(sprite->getPosition().x, sprite->getPosition().y); groundsize = sprite->getContentSize(); log("groundcounter==0"); } groundcounter++; log("groundcounter=%d", groundcounter); } else { if (groundcounter != 0) { log("make execute!"); groundsize = Size(groundsize.width*groundcounter, groundsize.height); log("point=%f %f,size=%f %f", groundpoint.x, groundpoint.y, groundsize.width, groundsize.height); this->makePhysicsObjAt(groundpoint, groundsize, false, 0, 0.0f, 0.0f, 0, GROUND_GID, -1); } groundcounter = 0; }///////////////// if (gid == DEAD_LINE_GID) { log("sssssssssss %f,ppppppppppppp %f", sprite->getPosition().x, sprite->getPosition().y); if (deadlinecounter == 0) { deadlinepoint = Point(sprite->getPosition().x, sprite->getPosition().y); deadlinesize = sprite->getContentSize(); log("groundcounter==0"); } deadlinecounter++; log("groundcounter=%d", deadlinecounter); } else { if (deadlinecounter != 0) { log("make execute!"); deadlinesize = Size(deadlinesize.width*deadlinecounter, deadlinesize.height); log("point=%f %f,size=%f %f", deadlinepoint.x, deadlinepoint.y, deadlinesize.width, deadlinesize.height); this->makePhysicsObjAt(deadlinepoint, deadlinesize, false, 0, 0.0f, 0.0f, 0, DEAD_LINE_GID, -1); } deadlinecounter = 0; } if (gid == CAN_DISPEAR_GID) { sprite->setTag(count); log("sprite->setTag(%d);", count); log("sssssssssss %f,ppppppppppppp %f", sprite->getPosition().x, sprite->getPosition().y); if (dispearcounter == 0) { dispearpoint = Point(sprite->getPosition().x, sprite->getPosition().y); dispearsize = sprite->getContentSize(); log("groundcounter==0"); } dispearcounter++; log("groundcounter=%d", dispearcounter); } else { if (dispearcounter != 0) { log("make execute!"); dispearsize = Size(dispearsize.width*dispearcounter, dispearsize.height); log("point=%f %f,size=%f %f", dispearpoint.x, dispearpoint.y, dispearsize.width, dispearsize.height); this->makePhysicsObjAt(dispearpoint, dispearsize, false, 0, 0.0f, 0.0f, 0, CAN_DISPEAR_GID, count); count++; } dispearcounter = 0; } if (gid == BODY_GID) { log("sssssssssss %f,ppppppppppppp %f", sprite->getPosition().x, sprite->getPosition().y); if (bodycounter == 0) { bodypoint = Point(sprite->getPosition().x, sprite->getPosition().y); bodysize = sprite->getContentSize(); log("groundcounter==0"); } bodycounter++; log("groundcounter=%d", bodycounter); } else { if (bodycounter != 0) { log("make execute!"); bodysize = Size(bodysize.width*bodycounter, bodysize.height); log("point=%f %f,size=%f %f", bodypoint.x, bodypoint.y, bodysize.width, bodysize.height); this->makePhysicsObjAt(bodypoint, bodysize, false, 0, 0.0f, 0.0f, 0, BODY_GID, -1); } bodycounter = 0; } if (count == 10000)count = 0; } } /******* 原始添加刚体算法,当刚体太多容易造成屏幕反应迟钝,故优化为以上算法 ************** for (int y = 0; y<TMX_HEIGHT; y++) { log("xxxxxxxxxxxxxxxxxxxx:%d",y); for (int x = 0; x<TMX_WIDTH; x++) { log("yyyyyyyyyyyyyyyyy:%d",x); int gid = layer->getTileGIDAt(Vec2(x, y));//为了提高点效率,我们没必要给每个tile加上刚体,在创建地图时我们设定了空白处的gid值为12,因此我们只对非12的tile加上刚体 log("GGIIDD %d",gid); switch (gid) { case GROUND_GID: { log("GGGGGGGGGGGGIIIIIIIIIIIIIDDDDDDDDDDDDD"); Sprite* sprite = layer->getTileAt(Vec2(x, y));//从tile的坐标取出对应的精灵 log("sssssssssss %f,ppppppppppppp %f", sprite->getPosition().x, sprite->getPosition().y); auto point = Point(sprite->getPosition().x, sprite->getPosition().y); auto size = Size(sprite->getContentSize().width, sprite->getContentSize().height); log("xxxxxxxxxxx %f,llllllllllll %f", sprite->getContentSize().width, sprite->getContentSize().height); this->makePhysicsObjAt(point, size, false, 0, 0.0f, 0.0f, 0, GROUND_GID,-1); }break; case DEAD_LINE_GID: { Sprite* sprite = layer->getTileAt(Vec2(x, y));//从tile的坐标取出对应的精灵 log("sssssssssss %f,ppppppppppppp %f", sprite->getPosition().x, sprite->getPosition().y); auto point = Point(sprite->getPosition().x, sprite->getPosition().y); auto size = Size(sprite->getContentSize().width, sprite->getContentSize().height); log("xxxxxxxxxxx %f,llllllllllll %f", sprite->getContentSize().width, sprite->getContentSize().height); this->makePhysicsObjAt(point, size, false, 0, 0.0f, 0.0f, 0, DEAD_LINE_GID,-1); }break; case CAN_DISPEAR_GID: { Sprite* sprite = layer->getTileAt(Vec2(x, y));//从tile的坐标取出对应的精灵 sprite->setTag(count); log("sssssssssss %f,ppppppppppppp %f", sprite->getPosition().x, sprite->getPosition().y); auto point = Point(sprite->getPosition().x, sprite->getPosition().y); auto size = Size(sprite->getContentSize().width, sprite->getContentSize().height); log("xxxxxxxxxxx %f,llllllllllll %f", sprite->getContentSize().width, sprite->getContentSize().height); this->makePhysicsObjAt(point, size, false, 0, 0.0f, 0.0f, 0, CAN_DISPEAR_GID,count); count++; }break; case BODY_GID: { log("GGGGGGGGGGGGIIIIIIIIIIIIIDDDDDDDDDDDDD"); Sprite* sprite = layer->getTileAt(Vec2(x, y));//从tile的坐标取出对应的精灵 log("sssssssssss %f,ppppppppppppp %f", sprite->getPosition().x, sprite->getPosition().y); auto point = Point(sprite->getPosition().x, sprite->getPosition().y); auto size = Size(sprite->getContentSize().width, sprite->getContentSize().height); log("xxxxxxxxxxx %f,llllllllllll %f", sprite->getContentSize().width, sprite->getContentSize().height); this->makePhysicsObjAt(point, size, false, 0, 0.0f, 0.0f, 0, GROUND_GID, -1); }break; default: break; } if (count == 10000)count = 0; } } */ /* //带物理的会动的 dead = DeadStar::create(); dead->initWithFile("dead.png"); dead->setAnchorPoint(Point(0, 0); dead->setPosition(visibleSize.width / 2 + 20, visibleSize.height / 3 + 400); dead->getPhysicsBody()->setContactTestBitmask(DEAD_LINE); this->addChild(dead); */ //加入障碍物 // auto obstacle1 = Obstacle::create(); // obstacle1->setAnchorPoint(Point(0, 0));// // obstacle1->setPosition(visibleSize.width / 2+300 , visibleSize.height /2); // obstacle1->getPhysicsBody()->setContactTestBitmask(OBJECT_BIT_MASK); // this->addChild(obstacle1); //加入圆形 /* auto circular = Circular::create(); circular->setPosition(visibleSize.width / 2 + 100, visibleSize.height / 3+50); circular->getPhysicsBody()->setContactTestBitmask(OBJECT_BIT_MASK); addChild(circular); auto circular2 = Circular::create(); circular2->setPosition(visibleSize.width / 2 + 100, visibleSize.height / 3 + 100); circular2->getPhysicsBody()->setContactTestBitmask(OBJECT_BIT_MASK); addChild(circular2);*/ //加入小怪兽 // MA1 = MonsterA::create(); // MA1->initWithFile("redcircle.png"); // MA1->setAnchorPoint(Point(0, 1));//////////////// // MA1->setPosition(visibleSize.width *2 + 60, visibleSize.height / 3 + 200); // MA1->getPhysicsBody()->setContactTestBitmask(MONSTER1_BIT_MASK); // log("MA1 - getTag();%d", MA1 - getTag()); // this->addChild(MA1); // 设置准确位置,放置怪兽; auto printM1 = objects->getObject("monster1"); // CCASSERT(!printM1.empty(), "SpawnPoint object not found"); int x1 = printM1["x"].asInt(); int y1 = printM1["y"].asInt(); // auto _player = Sprite::create("orangetriangle.png"); auto player1 = MonsterD::create(); //player1->initWithFile("orangetriangle.png"); player1->setAnchorPoint(Point(0, 1)); player1->setPosition(x1, y1); player1->getPhysicsBody()->setContactTestBitmask(MONSTER1_BIT_MASK); addChild(player1); //setViewPointCenter(_player->getPosition()); auto printM2 = objects->getObject("monster2"); // CCASSERT(!printM2.empty(), "SpawnPoint object not found"); int x2 = printM2["x"].asInt(); int y2 = printM2["y"].asInt(); // auto _player = Sprite::create("orangetriangle.png"); auto player2 = MonsterD::create(); //player2->initWithFile("orangetriangle.png"); player2->setAnchorPoint(Point(0, 1)); player2->setPosition(x2, y2); player2->getPhysicsBody()->setContactTestBitmask(MONSTER1_BIT_MASK); addChild(player2); auto printM3 = objects->getObject("monster3"); // CCASSERT(!printM3.empty(), "SpawnPoint object not found"); int x3 = printM3["x"].asInt(); int y3 = printM3["y"].asInt(); // auto _player = Sprite::create("orangetriangle.png"); auto player3 = MonsterD::create(); //player2->initWithFile("orangetriangle.png"); player3->setAnchorPoint(Point(0, 1)); player3->setPosition(x3, y3); player3->getPhysicsBody()->setContactTestBitmask(MONSTER1_BIT_MASK); addChild(player3); auto printM4 = objects->getObject("monster4"); // CCASSERT(!printM4.empty(), "SpawnPoint object not found"); int x4 = printM4["x"].asInt(); int y4 = printM4["y"].asInt(); // auto _player = Sprite::create("orangetriangle.png"); auto player4 = MonsterD::create(); //player1->initWithFile("orangetriangle.png"); player4->setAnchorPoint(Point(0, 1)); player4->setPosition(x4, y4); player4->getPhysicsBody()->setContactTestBitmask(MONSTER1_BIT_MASK); addChild(player4); //setViewPointCenter(_player->getPosition()); auto printM5 = objects->getObject("monster5"); // CCASSERT(!printM5.empty(), "SpawnPoint object not found"); int x5 = printM5["x"].asInt(); int y5 = printM5["y"].asInt(); // auto _player = Sprite::create("orangetriangle.png"); auto player5 = MonsterD::create(); //player2->initWithFile("orangetriangle.png"); player5->setAnchorPoint(Point(0, 1)); player5->setPosition(x5, y5); player5->getPhysicsBody()->setContactTestBitmask(MONSTER1_BIT_MASK); addChild(player5); auto printM6 = objects->getObject("monster6"); // CCASSERT(!printM6.empty(), "SpawnPoint object not found"); int x6 = printM6["x"].asInt(); int y6 = printM6["y"].asInt(); // auto _player = Sprite::create("orangetriangle.png"); auto player6 = MonsterD::create(); //player2->initWithFile("orangetriangle.png"); player6->setAnchorPoint(Point(0, 1)); player6->setPosition(x6, y6); player6->getPhysicsBody()->setContactTestBitmask(MONSTER1_BIT_MASK); addChild(player6); auto printM7 = objects->getObject("monster7"); // CCASSERT(!printM1.empty(), "SpawnPoint object not found"); int x7 = printM7["x"].asInt(); int y7 = printM7["y"].asInt(); // auto _player = Sprite::create("orangetriangle.png"); auto player7 = MonsterD::create(); //player1->initWithFile("orangetriangle.png"); player7->setAnchorPoint(Point(0, 1)); player7->setPosition(x7, y7); player7->getPhysicsBody()->setContactTestBitmask(MONSTER1_BIT_MASK); addChild(player7); //setViewPointCenter(_player->getPosition()); //加入门 auto door = Ground::create(); door->groundSize = Size(visibleSize.width / 6, visibleSize.height/4); door->init(door->groundSize); door->getPhysicsBody()->setContactTestBitmask(DOOR_BIT_MASK); //stage1->setAnchorPoint(Point(0, 1));visibleSize.width / 2, visibleSize.height / 3 door->setPosition(door->groundSize.width / 2 + visibleSize.width * 5, door->groundSize.height / 2 + visibleSize.height / 3); addChild(door); auto doorpicture = Sprite::create("road_5.png"); //静态的,为不动的刚体添加图片使用这种方式 doorpicture->setAnchorPoint(Point(0, 0)); doorpicture->setPosition(visibleSize.width * 5, visibleSize.height / 3); this->addChild(doorpicture);// //加入桥 /* bridge = Board::create(); bridge->setPosition(100, 100); bridge->setPosition(visibleSize.width / 2 + 20, visibleSize.height / 3 + 200); addChild(bridge);*/ state = 0; scheduleUpdate(); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ){ return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); /* REGISTERING TOUCH EVENTS ===================================================== */ auto controls = EventListenerTouchAllAtOnce::create(); controls->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(controls, this); /* NOTE: don't get in the habit of using auto everywhere An iron price to be paid (extra time == life) masquerading as convenience No reference can be made with auto and makes code unreadable Justified here since controls is a one-off and will not be referenced anywhere else but in this temporal block ALSO: This is what is called a observer pattern in the industry controls would be an "interface" of known `subscribers` to the _eventDispatcher `publisher` and events are "published" to the subscribers as they happen. Interface just means a contractual agreement between different parts of code to follow a uniform language */ /* CREATE A TMXTILEDMAP AND EXTRACT LAYER FOR DISPLAY ===================================================== */ _tileMap = TMXTiledMap::create("TileMap.tmx"); // DEPRECATED: _tileMap = new CCTMXTiledMap(); // _tileMap->initWithTMXFile("TileMap.tmx"); _background = _tileMap->getLayer("Background"); // DEPRECATED: _tileMap->layerNamed("Background"); _meta = _tileMap->layerNamed("Meta"); _meta->setVisible(false); this->addChild(_tileMap); TMXObjectGroup *objectGroup = _tileMap->objectGroupNamed("Objects"); // DEPRECATED: CCTMXObjectGroup *objectGroup = _tileMap->objectGroupNamed("Objects"); if(objectGroup == NULL) { CCLOG("tile map has no Objects object layer"); // DEPRECATED: CCLog("tile map has no objects object layer"); return false; } ValueMap spawnPoint = objectGroup->objectNamed("SpawnPoint"); // DEPRECATED: CCDictionary *spawnPoint = objectGroup->objectNamed("SpawnPoint"); Vec2 spawnHere = Point(300, 300); if(spawnPoint.size() != 0) { CCLOG("LOGCAT!!! There is a spawn point"); } else { CCLOG("LOGCAT!!! There isn't a spawn point. Using default 300 x 300."); } _player = Sprite::create("Player.png"); _player->setPosition(spawnHere); this->addChild(_player); this->setViewPointCenter(_player->getPosition()); this->setTouchEnabled(true); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // create menu, it's an autorelease object // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); 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 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 ShowLayer::loadConfig(int level) { Size visibleSize = Director::getInstance()->getVisibleSize(); m_Level = level; //初始化随机种子 randNum(); if (level == 3) { int rand = CCRANDOM_0_1() * 5; //加载地图资源 m_Map = CCTMXTiledMap::create("LastMap2.tmx"); m_MaxLength = 1600; m_MinLength = 0; //获取地图上player的坐标 TMXObjectGroup* objGoup = m_Map->getObjectGroup("playerPoint"); ValueMap playerPointMap = objGoup->getObject("Player"); float playerX = playerPointMap.at("x").asFloat(); float playerY = playerPointMap.at("y").asFloat(); //创建playerManager m_PlayerManager = PlayerManager::createWithLevel(Vec2(playerX, playerY + 24), level); m_PlayerManager->setPosition(Vec2(0, 0)); m_Map->addChild(m_PlayerManager, 3); //获取地图上怪物坐标 TMXObjectGroup* mobjGoup = m_Map->getObjectGroup("monsterPoint"); ValueVector monsterPoints = mobjGoup->getObjects(); //ValueMap monsterPoint = mobjGoup->getObject("monster1"); //float monsterX = monsterPoint.at("x").asFloat(); //float monsterY = monsterPoint.at("y").asFloat(); PhyscisWorld::createWorld(m_Map, level); //创建monsterManager m_MonsterManager = MonsterManager::createWithLevel(monsterPoints, level); //change m_MonsterManager->setAnchorPoint(Vec2(0, 0)); m_MonsterManager->setPosition(Vec2(0, 0)); m_Map->addChild(m_MonsterManager, 2); TMXObjectGroup* bobjGoup = m_Map->getObjectGroup("Boss"); ValueMap bossPoint = bobjGoup->getObject("boss"); float bossPointX = bossPoint.at("x").asFloat(); float bossPointY = bossPoint.at("y").asFloat(); m_BossManager = BossManager::createWithLevel(Vec2(bossPointX, bossPointY), level); m_BossManager->setAnchorPoint(Vec2(0, 0)); m_BossManager->setPosition(Vec2(0, 0)); m_BossManager->setBOrigin(Vec2(bossPointX, bossPointY)); m_Map->addChild(m_BossManager, 2); //m_boss->setOrigin(Vec2(bossPointX, bossPointY)); //m_boss->setPosition(Vec2(bossPointX, bossPointY)); //this->addChild(m_boss, 3); m_GodArmManager = GodArmManager::createWithLevel(1, m_PlayerManager, m_MonsterManager, m_BossManager); m_GodArmManager->setPosition(Vec2(0, 0)); m_Map->addChild(m_GodArmManager, 4); m_GodArmManager->runPower(); this->schedule(schedule_selector(ShowLayer::Monsterlogic), 0.1f); this->schedule(schedule_selector(ShowLayer::logic), 1 / 20.0f); this->schedule(schedule_selector(ShowLayer::Bosslogic), 1.0f); //认领地图 this->addChild(m_Map, 0, 1); } }
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } // Add sounds/effect SimpleAudioEngine::getInstance()->preloadEffect("error.mp3"); SimpleAudioEngine::getInstance()->preloadEffect("item.mp3"); SimpleAudioEngine::getInstance()->preloadEffect("step.mp3"); SimpleAudioEngine::getInstance()->preloadEffect("wade.mp3"); SimpleAudioEngine::getInstance()->playBackgroundMusic("background.mp3"); SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(0.1); // Load the tile map std::string file = "01.tmx"; auto str = String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(file.c_str()).c_str()); _tileMap = TMXTiledMap::createWithXML(str->getCString(),""); _background = _tileMap->layerNamed("Background"); _foreground = _tileMap->layerNamed("Foreground01"); _layer01 = _tileMap->layerNamed("Layer01"); _layer02 = _tileMap->layerNamed("Layer02"); _layer03 = _tileMap->layerNamed("Layer03"); _cross = _tileMap->layerNamed("CanCross01"); _cross->setVisible(false); _blockage = _tileMap->layerNamed("Blockage01"); _blockage->setVisible(false); addChild(_tileMap, -1); // Position of the player TMXObjectGroup *objects = _tileMap->getObjectGroup("Object-Player"); CCASSERT(NULL != objects, "'Object-Player' object group not found"); auto playerShowUpPoint = objects->getObject("PlayerShowUpPoint"); CCASSERT(!playerShowUpPoint.empty(), "PlayerShowUpPoint object not found"); int x = playerShowUpPoint["x"].asInt(); int y = playerShowUpPoint["y"].asInt(); _player = Sprite::create("029.png"); _player->setPosition(x + _tileMap->getTileSize().width / 2, y + _tileMap->getTileSize().height / 2); _player->setScale(0.5); addChild(_player); setViewPointCenter(_player->getPosition()); // Position of the enemy for (auto& eSpawnPoint: objects->getObjects()){ ValueMap& dict = eSpawnPoint.asValueMap(); if(dict["Enemy"].asInt() == 1){ x = dict["x"].asInt(); y = dict["y"].asInt(); this->addEnemyAtPos(Point(x, y)); } } // Event listener touch auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [&](Touch *touch, Event *unused_event)->bool {return true;}; listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this); this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); _numCollected = 0; _mode = 0; this->schedule(schedule_selector(HelloWorld::testCollisions)); return true; }
// on "init" you need to initialize your instance bool TileMap::init() { if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); _visibleSize = visibleSize; _origin = origin; auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(TileMap::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); auto label = LabelTTF::create("TileMap", "Arial", 24); label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); this->addChild(label, 1); _tileMap = TMXTiledMap::create("bg_TileMap.tmx"); _tileMap->setPosition(Vec2(0,0)); // _tileMap->setScale(_visibleSize.width/_tileMap->getContentSize().width,_visibleSize.height/_tileMap->getContentSize().height); _tileMap->setVisible(true); _background = _tileMap->layerNamed("bg"); _collidable = _tileMap->layerNamed("Meta"); _collidable->setVisible(false); Director::getInstance()->setProjection(Director::Projection::_2D); this->addChild(_tileMap, 0, 50); TMXObjectGroup *group = _tileMap->getObjectGroup("Objects"); ValueMap spawnPoint = group->getObject("SpawnPoint"); float x = spawnPoint["x"].asFloat(); float y = spawnPoint["y"].asFloat(); // ActorManager::getInstance()->_actorTarget = new Vector<Actor*>(50); // ActorManager::getInstance()->_monsterTarget = Vector<Actor*>(50); _actor = Actor::create(); _player = Sprite::create("ninja.png"); _player->setTag(100); _player->setPosition(Vec2(x,y)); // _posInScreen = Vec2(x,y); this->addChild(_player, 2); auto bld = new ActorBlood(100); _actor->setActorSprite(_player); _actor->setActorTag(1); _actor->setActorBlood(bld); ActorManager::getInstance()->_actorTarget.pushBack(_actor); _collision = new CollisionBlood(this, ActorManager::getInstance()->_monsterTarget); for (int i=1; i<6; i++) { ValueMap point = group->getObject("target"+Value(i).asString()); float x = point["x"].asFloat(); float y = point["y"].asFloat(); std::string str = "BasiliskBrown.PNG"; _collision->addTarget(Vec2(x,y), str); } /* * screen Touch */ _listener = EventListenerTouchOneByOne::create(); _listener->onTouchBegan = CC_CALLBACK_2(TileMap::onTouchBegan,this); _listener->onTouchMoved = CC_CALLBACK_2(TileMap::onTouchMoved,this); _listener->onTouchEnded = CC_CALLBACK_2(TileMap::onTouchEnded,this); _listener->setSwallowTouches(true);//²»ÏòÏ´«µÝ´¥Ãþ _eventDispatcher->addEventListenerWithSceneGraphPriority(_listener,this); //_listener->setEnabled(false); /* * AstartPathFinding */ AstartPathFinding* astart = new AstartPathFinding(_tileMap->getMapSize().width, _tileMap->getMapSize().height); _astart = astart; astart->mapInit(); for (int i=0; i<_tileMap->getMapSize().width; i++) for (int j=0; j<_tileMap->getMapSize().height; j++) { if (checkNodePassable(Vec2(i,_tileMap->getMapSize().height-j-1)) == false) astart->getMap(i,j)->setPassable(false); } // for (int i=0; i<_tileMap->getMapSize().width; i++) // for (int j=0; j<_tileMap->getMapSize().height; j++) { // log("checkNodePassable_[%d][%d] = %d",i, j,_astart->getMap(i,j)->getPassable()); // } // log("_tileMap->getMapSize().width = %f",_tileMap->getMapSize().width); // log("_tileMap->getMapSize().height = %f",_tileMap->getMapSize().height); this->scheduleUpdate(); return true; }