void MapScene::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) { CCSetIterator it = pTouches->begin(); CCTouch* touch = (CCTouch*)(*it); CCPoint m_tBeginPos = touch->getLocationInView(); m_tBeginPos = CCDirector::sharedDirector()->convertToGL( m_tBeginPos ); char mch[256]; CCTMXTiledMap* map = (CCTMXTiledMap*) getChildByTag(kTagTileMap); CCPoint mapp = map->getPosition(); //获得触摸点位置在地图上的索引(行列) CCPoint aimmapindex = convertto2d(m_tBeginPos.x - mapp.x,m_tBeginPos.y - mapp.y); if(aimmapindex.x < 0 || aimmapindex.y < 0 || aimmapindex.x >= map->getMapSize().width || aimmapindex.y >= map->getMapSize().height) { return; } CCPoint herop = m_tamara->getPosition(); CCPoint mapindex = convertto2d(herop.x,herop.y); CCTMXLayer* layer = map->layerNamed("grass"); int tilegid = layer->tileGIDAt(ccp(aimmapindex.x,aimmapindex.y)); CCDictionary *tiledic = map->propertiesForGID(tilegid); CCString *mvalue = (CCString *)tiledic->objectForKey("conflict"); int mv = mvalue->intValue(); if(mv == 1){ return; } //A星搜索 path = myastar->findPath(mapindex.x,mapindex.y,aimmapindex.x,aimmapindex.y,map); stepindex = 1; smallstepindex = 0; }
void RoadScene::Event_1(){ CCTMXLayer * layer = map->layerNamed("entrance_covered"); layer->setVisible(false); CCRPGTalkBox* box1 = CCRPGTalkBox::create(13, "dialog-box.png", "2_3.txt", 13, CCSizeMake(800, 200), 1,callfunc_selector(RoadScene::GoToNextStage),this,screenpos); addChild(box1,9999,13); box1->NextText(); }
void MyBattleMap::initCostMap() { CCTMXLayer* layer = this->layerNamed("tiled"); CCSize size = this->getMapSize(); const char* str; int cost = 0; costMap = new int*[(int)size.width]; for(int i = 0; i < size.width; i++) { costMap[i] = new int[(int)size.height]; } for (int i=0; i<size.width; ++i) { for (int j=0; j<size.height; ++j) { str = ((CCString*) this->propertiesForGID(layer->tileGIDAt(ccp(i,j)))->objectForKey("cost"))->getCString(); costMap[i][j] = sscanf(str, "%d", &cost); } } mybuildingMap = new CCObject**[(int)size.width+2]; for(int i = 0; i < size.width+2; i++) { mybuildingMap[i] = new CCObject*[(int)size.height+2]; } for (int i=0; i<size.width+2; ++i) { for (int j=0; j<size.height+2; ++j) { mybuildingMap[i][j] = NULL; } } // layer->get // if (Mathlib::inBound(int(tiled.x+0.5),this->getMapSize().width-1 , 0)&&Mathlib::inBound(int(tiled.y+0.5),this->getMapSize().height-1 , 0)) { // //// CCLog("TransX:%f,transY:%f",ceil(tiled.x),ceil(tiled.y)); // layer->setTileGID(3,ccp(int(tiled.x+0.5),int(tiled.y+0.5))); // } }
void MapScene::playermapvcollision(){ //主角与地图竖直(下)图素的碰撞检测 CCPoint playerpoint = gameplayer->getPosition(); CCSize palyersize = gameplayer->getContentSize(); CCTMXTiledMap* map = (CCTMXTiledMap*) getChildByTag(kTagTileMap); int indexx,indexy; CCTMXLayer* layer = map->layerNamed("logic"); //人物下边界 indexx = (playerpoint.x) / map->getTileSize().width; indexy = map->getMapSize().height - (playerpoint.y) / map->getTileSize().height; CCPoint playerindex = ccp(indexx,indexy); int tilegid = layer->tileGIDAt(playerindex); if(tilegid > 0){ CCDictionary *tiledic = map->propertiesForGID(tilegid); CCString *mvalue = (CCString *)tiledic->objectForKey("collion"); int mv = mvalue->intValue(); if(mv == 1){ if(vmove < 0){ vmove = 0; hmove = 0; playerpoint.y = (map->getMapSize().height - indexy) * map->getTileSize().height; gameplayer->setPosition(playerpoint); } return; } } vmove -= 0.2; }
void Soko::spriteMoveFinished(CCNode *sender) { mpPlayer->mIsMoving = false; int mapYSize = this->getTileMap()->getMapSize().height; CCTMXLayer *pTMGround = this->getTileMap()->layerNamed("Ground"); // Change the boxes to show whether they are on a goal spot or not // This code is a bit of a duplicate of the code that moves the boxes, // but I don't want to do the update until the move completes int GoalCount = 0; int BoxCount = 0; CCArray *pBoxes = this->getTileMap()->getChildren(); for(int i=0; i<pBoxes->count(); ++i) { CCSprite *pBox = (CCSprite *)pBoxes->objectAtIndex(i); if (pBox->getTag() == 1) { // Need to actually count these as tile map has children other than // just the boxes, such as the player and any effects I might add ++BoxCount; int boxXCell = (pBox->getPosition().x-32) / 64; int boxYCell = mapYSize - 1 - ((pBox->getPosition().y-32) / 64); if (pTMGround->tileGIDAt( ccp(boxXCell, boxYCell) ) == 2) { // On floor pBox->setTextureRect(CCRectMake(64,0,64,64)); } else if (pTMGround->tileGIDAt( ccp(boxXCell, boxYCell) ) == 3) { // On goal ++GoalCount; pBox->setTextureRect(CCRectMake(128,0,64,64)); } } } ostringstream movesStr; movesStr << "Moves: " << setw(4) << setfill('0') << mpPlayer->mMoveCount; ostringstream pushesStr; pushesStr << "Pushes: " << setw(4) << setfill('0') << mpPlayer->mPushCount; // NB This crashed when I used TTFLabels mpMovesLabel->setString(movesStr.str().c_str()); mpPushesLabel->setString(pushesStr.str().c_str()); if (GoalCount == BoxCount) { // Win! mGameRunning = false; // Fade label in and bounce its size a little mpLevelCompleteLabel->runAction(CCFadeIn::actionWithDuration(0.5)); mpLevelCompleteLabel->runAction( CCSequence::actions( CCScaleTo::actionWithDuration( (ccTime)0.25, 1.10 ), CCScaleTo::actionWithDuration( (ccTime)0.25, 1.00 ), NULL) ); } }
// CCTMXLayer - init & alloc & dealloc CCTMXLayer * CCTMXLayer::layerWithTilesetInfo(CCTMXTilesetInfo *tilesetInfo, CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo) { CCTMXLayer *pRet = new CCTMXLayer(); if (pRet->initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo)) { pRet->autorelease(); return pRet; } return NULL; }
// private CCTMXLayer * CCTMXTiledMap::parseLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo) { CCTMXTilesetInfo *tileset = tilesetForLayer(layerInfo, mapInfo); CCTMXLayer *layer = CCTMXLayer::create(tileset, layerInfo, mapInfo); // tell the layerinfo to release the ownership of the tiles map. layerInfo->m_bOwnTiles = false; layer->setupTiles(); return layer; }
CCSprite* CMGameMap::TileMapLayerPosToTileSprite( CCPoint TileMapLayerPos) { do { CCPoint TileMapPos = TileMapLayerPosToTileMapPos(TileMapLayerPos); //获得地图的各个层 CCTMXLayer* pCloudLayer = layerNamed("cloud"); CC_BREAK_IF(pCloudLayer==NULL); CCTMXLayer* pBlockLayer = layerNamed("block"); CC_BREAK_IF(pBlockLayer==NULL); CCTMXLayer* pPipeLayer = layerNamed("pipe"); CC_BREAK_IF(pPipeLayer==NULL); CCTMXLayer* pLandLayer = layerNamed("land"); CC_BREAK_IF(pLandLayer==NULL); CCTMXLayer* pTrapLayer = layerNamed("trap"); CC_BREAK_IF(pTrapLayer==NULL); CCTMXObjectGroup* pObjectLayer = objectGroupNamed("objects"); CC_BREAK_IF(pObjectLayer==NULL); CCTMXLayer* pCoinLayer = layerNamed("coin"); CC_BREAK_IF(pCoinLayer==NULL); CCTMXLayer* pFlagpoleLayer = layerNamed("flagpole"); CC_BREAK_IF(pFlagpoleLayer==NULL); //若马里奥超过上边界 if(TileMapPos.y<0)return NULL; CCSprite* pLandSprite = pLandLayer->tileAt(ccp(TileMapPos.x,TileMapPos.y)); if (pLandSprite!=NULL) { return pLandSprite; } CCSprite* pBlockSprite = pBlockLayer->tileAt(ccp(TileMapPos.x,TileMapPos.y)); if (pBlockSprite!=NULL) { //遍历砖块数组,如果砖块数组中未找到,则说明已被顶坏,返回空 CCObject *pObj = NULL; CCARRAY_FOREACH(m_pArrayBlocks,pObj) { CMItemBlock* pItem = dynamic_cast<CMItemBlock*>(pObj); CC_BREAK_IF(pItem==NULL); CCPoint CurBlockWorldPos = (pBlockSprite->getPosition()); CCPoint TempBlockWorldPos = (pItem->getPosition()); //找到则返回砖块精灵 if (abs(CurBlockWorldPos.x==TempBlockWorldPos.x) && abs(CurBlockWorldPos.y==TempBlockWorldPos.y)) { return pBlockSprite; } } return NULL; }
NS_CC_BEGIN // CCTMXLayer - init & alloc & dealloc CCTMXLayer * CCTMXLayer::create(CCTMXTilesetInfo *tilesetInfo, CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo) { CCTMXLayer *pRet = new CCTMXLayer(); if (pRet->initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo)) { pRet->autorelease(); return pRet; } return NULL; }
bool Astar::checkmap(int col,int row) { //检查地图中是否有碰撞 if(abs(aimCol - col) > 1 || abs(aimRow - row) > 1){ CCTMXLayer* layer = map->layerNamed("grass"); int tilegid = layer->tileGIDAt(ccp(col,row)); CCDictionary *tiledic = map->propertiesForGID(tilegid); CCString *mvalue = (CCString *)tiledic->objectForKey("conflict"); int mv = mvalue->intValue(); if(mv == 1){ return false; } } return true; }
void BattleMap::f_decide(int i, int j){ //通过新的选中tile对map进行重构。 use the set to decide. imply_set(ts_last,0); ts_last.clear(); CCTMXTiledMap* map = (CCTMXTiledMap*) getChildByTag(kTagMap); CCTMXLayer* layer = map->layerNamed("Battle"); unsigned int gid = layer->tileGIDAt(ccp(i,j)); draw_mouse_range(ccp(i,j)); m_mou_cur = ccp(i,j); imply_set(ts_last,c_r); imply_set(cs_dis,c_b); //blue is higher than red. }
bool CCTMXTiledMap::initWithTMXFile(const char *tmxFile) { NSAssert(tmxFile != NULL && strlen(tmxFile)>0, "TMXTiledMap: tmx file should not bi nil"); setContentSize(CGSizeZero); CCTMXMapInfo *mapInfo = CCTMXMapInfo::formatWithTMXFile(tmxFile); NSAssert( mapInfo->getTilesets()->count() != 0, "TMXTiledMap: Map not found. Please check the filename."); m_tMapSize = mapInfo->getMapSize(); m_tTileSize = mapInfo->getTileSize(); m_nMapOrientation = mapInfo->getOrientation(); setObjectGroups(mapInfo->getObjectGroups()); setProperties(mapInfo->getProperties()); CCX_SAFE_RELEASE(m_pTileProperties); m_pTileProperties = mapInfo->getTileProperties(); CCX_SAFE_RETAIN(m_pTileProperties); int idx = 0; NSMutableArray<CCTMXLayerInfo*>* layers = mapInfo->getLayers(); if (layers && layers->count()>0) { CCTMXLayerInfo *layerInfo = NULL; NSMutableArray<CCTMXLayerInfo*>::NSMutableArrayIterator it; for (it = layers->begin(); it != layers->end(); ++it) { layerInfo = *it; if (layerInfo && layerInfo->m_bVisible) { CCTMXLayer *child = parseLayer(layerInfo, mapInfo); addChild((CCNode*)child, idx, idx); // update content size with the max size CGSize childSize = child->getContentSize(); CGSize currentSize = this->getContentSize(); currentSize.width = MAX( currentSize.width, childSize.width ); currentSize.height = MAX( currentSize.height, childSize.height ); this->setContentSize(currentSize); idx++; } } } return true; }
void MapScene::playermaphcollision(){ //主角与地图水平(左右)图素的碰撞检测 CCPoint playerpoint = gameplayer->getPosition(); CCSize palyersize = gameplayer->getContentSize(); CCTMXTiledMap* map = (CCTMXTiledMap*) getChildByTag(kTagTileMap); int indexx,indexy; char mch[256]; CCTMXLayer* layer = map->layerNamed("logic"); //遍历图素块 for(int playery = playerpoint.y - palyersize.height;playery <= playerpoint.y;playery ++){ //人物左边界 indexx = (playerpoint.x - palyersize.width / 2) / map->getTileSize().width; indexy = (playerpoint.y) / map->getTileSize().height; CCPoint playerindex = ccp(indexx,indexy); int tilegid = layer->tileGIDAt(playerindex); if(tilegid > 0){ //如果碰撞,设置主角位置 CCDictionary *tiledic = map->propertiesForGID(tilegid); CCString *mvalue = (CCString *)tiledic->objectForKey("collion"); int mv = mvalue->intValue(); if(mv == 2){ hmove = 0; playerpoint.x = (indexx + 1) * map->getTileSize().width + palyersize.width / 2; gameplayer->setPosition(playerpoint); } return; } //人物右边界 indexx = (playerpoint.x + palyersize.width / 2 - 1) / map->getTileSize().width; indexy = (playerpoint.y) / map->getTileSize().height; playerindex = ccp(indexx,indexy); tilegid = layer->tileGIDAt(playerindex); if(tilegid > 0){ //如果碰撞,设置主角位置 CCDictionary *tiledic = map->propertiesForGID(tilegid); CCString *mvalue = (CCString *)tiledic->objectForKey("collion"); int mv = mvalue->intValue(); if(mv == 2){ hmove = 0; playerpoint.x = (indexx) * map->getTileSize().width - palyersize.width / 2; gameplayer->setPosition(playerpoint); } return; } } }
bool TileMap::canPassedCOLROW(cocos2d::CCPoint pos){ CCLayer *layer = this->getLayer(); CCTMXTiledMap *tileMap = dynamic_cast<CCTMXTiledMap*>(layer->getChildByTag(tilemap_tag)); //获得block层 CCTMXLayer *block = tileMap->layerNamed("block"); //获得砖块(根据某个位置) int tileGID = block->tileGIDAt(pos); if (tileGID) { CCDictionary *properties = tileMap->propertiesForGID(tileGID); if (properties) { const CCString *collion = properties->valueForKey("blockTiled"); if (collion&&collion->compare("1")) { return true; } } } return true; }
void MyScene::addBackground(){ CCTMXTiledMap* pTmap = CCTMXTiledMap::create("TileMaps/TestDesert.tmx"); pTmap->setName("Tmap"); backgroundNode = CCParallaxNode::create(); backgroundNode->setName("Background"); backgroundNode->addChild(pTmap, 1, ccp(1.0f, 1.0f), ccp(0, 0)); this->addChild(backgroundNode, 0); CCTMXObjectGroup* objects = pTmap->objectGroupNamed("Objects"); ValueMap& spawnPoint = objects->getObject("SpawnPoint"); CCTMXLayer* metaInfo = pTmap->getLayer("MetaInfo"); metaInfo->setVisible(false); //create a dragon on "SpawnPoint" int x = spawnPoint["x"].asInt(); int y = spawnPoint["y"].asInt(); this->createDragon(CCPoint(ccp(x, y))); }
// public CCTMXLayer * CCTMXTiledMap::layerNamed(const char *layerName) { std::string sLayerName = layerName; if (m_pChildren && m_pChildren->count()>0) { CCTMXLayer *layer; NSMutableArray<CCNode*>::NSMutableArrayIterator it; for (it = m_pChildren->begin(); it != m_pChildren->end(); ++it) { layer = (CCTMXLayer*)(*it); if (layer && layer->getLayerName() == sLayerName) { return layer; } } } // layer not found return NULL; }
bool CCTMXTiledMap::initWithTMXFile(const char *tmxFile) { CCAssert(tmxFile != NULL && strlen(tmxFile)>0, "TMXTiledMap: tmx file should not bi nil"); setContentSize(CCSizeZero); CCTMXMapInfo *mapInfo = CCTMXMapInfo::formatWithTMXFile(tmxFile); if (! mapInfo) { return false; } CCAssert( mapInfo->getTilesets()->count() != 0, "TMXTiledMap: Map not found. Please check the filename."); m_tMapSize = mapInfo->getMapSize(); m_tTileSize = mapInfo->getTileSize(); m_nMapOrientation = mapInfo->getOrientation(); setObjectGroups(mapInfo->getObjectGroups()); setProperties(mapInfo->getProperties()); CC_SAFE_RELEASE(m_pTileProperties); m_pTileProperties = mapInfo->getTileProperties(); CC_SAFE_RETAIN(m_pTileProperties); int idx = 0; CCMutableArray<CCTMXLayerInfo*>* layers = mapInfo->getLayers(); if (layers && layers->count()>0) { if (NULL == m_pTMXLayers) { m_pTMXLayers = new CCDictionary<std::string, CCTMXLayer*>(); CCAssert(m_pTMXLayers, "Allocate memory failed!"); } CCTMXLayerInfo *layerInfo = NULL; CCMutableArray<CCTMXLayerInfo*>::CCMutableArrayIterator it; for (it = layers->begin(); it != layers->end(); ++it) { layerInfo = *it; if (layerInfo && layerInfo->m_bVisible) { CCTMXLayer *child = parseLayer(layerInfo, mapInfo); addChild((CCNode*)child, idx, idx); // record the CCTMXLayer object by it's name std::string layerName = child->getLayerName(); m_pTMXLayers->setObject(child, layerName); // update content size with the max size const CCSize& childSize = child->getContentSize(); CCSize currentSize = this->getContentSize(); currentSize.width = MAX( currentSize.width, childSize.width ); currentSize.height = MAX( currentSize.height, childSize.height ); this->setContentSize(currentSize); idx++; } } } return true; }
bool BattleMap::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } m_notuseditems = new CCArray(); m_touch = NULL; m_caTarget = NULL; m_caTarCharas = NULL; cancontrol = false; vx= 0;vy = 0; m_touch = NULL; b_battle = -1; m_mi=-1;m_mj=-1; cs_y.clear();cs_r.clear();cs_b.clear(); //2. TileMap初始化 CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache(); sheet = CCSpriteBatchNode::create("Images/test.png"); cache->addSpriteFramesWithFile("Images/test.plist"); CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); m_tilemap = CCTMXTiledMap::create(CCString::createWithFormat("map/%s.tmx",map_path.c_str())->getCString()); addChild(m_tilemap, MapdDepth, kTagMap); CCSize s = m_tilemap->getContentSize(); CCSize winSize = CCDirector::sharedDirector()->getWinSize(); m_tilemap->setAnchorPoint(ccp(0, 0)); CCSize ms = m_tilemap->getMapSize(); CCSize ts = m_tilemap->getTileSize(); float r = (ms.width + ms.height) / 2; rw = r * ts.width; rh = r * ts.height; max_x = m_tilemap->getMapSize().width; max_y = m_tilemap->getMapSize().height; int mapWidth = m_tilemap->getMapSize().width * m_tilemap->getTileSize().width; int mapHeight = m_tilemap->getMapSize().height * m_tilemap->getTileSize().height; x0 = (ms.height - 1) * ts.width / 2; y0 = rh - ts.height; dtx = ts.width / 2; dty = ts.height / 2; dx = rw-mapWidth; dy = rh-mapHeight; m_tilemap->setPosition(ccp(0,0)); x0 -= dx; y0 -= dy; //3. b2world初始化 ////////////////////////////////////////////////////////////////////////// b2Vec2 gravity = b2Vec2(0.0f, 0.0f); _world = new b2World(gravity); colse = new MyContactListener(); _world->SetContactListener(colse); b2BodyDef groundBodyDef; groundBodyDef.position.Set(0.0f, 0.0f); // 设置位置 b2Body *groundBody = _world->CreateBody(&groundBodyDef); b2ChainShape chain; //使用chain将地图包围起来 b2FixtureDef sd; sd.shape = &chain; sd.density = 0.0f; sd.restitution = 0.0f; // Edge 的弹性如何~ b2Vec2 vs[4]; vs[0].Set((ms.height * ts.width/2 -dx)/ PTM_RATIO, (rh - dy) / PTM_RATIO); vs[1].Set((rw - dx) / PTM_RATIO, (ms.height * ts.height/2 - dy) / PTM_RATIO); vs[2].Set((ms.width * ts.width/2 - dx) / PTM_RATIO, -dy/PTM_RATIO); vs[3].Set(-dx/PTM_RATIO, (ms.width * ts.height/2 - dy )/ PTM_RATIO); chain.CreateLoop(vs, 4); Entiles* kted = new Entiles(); kted->name = "edge"; groundBody->SetUserData(kted); groundBody->CreateFixture(&sd); m_notuseditems->addObject(kted); ////////////////////////////////////////////////////////////////////////// #ifdef DEBUGDRAW m_debugDraw = new GLESDebugDraw( PTM_RATIO ); _world->SetDebugDraw(m_debugDraw); unsigned int flags = 0; flags += b2Draw::e_shapeBit; flags += b2Draw::e_jointBit; flags += b2Draw::e_aabbBit; flags += b2Draw::e_pairBit; flags += b2Draw::e_centerOfMassBit; m_debugDraw->SetFlags(flags); #endif ////////////////////////////////////////////////////////////////////////// if(!f_load_entile()) return false; if(m_itemlist->count() < 1) CC_SAFE_RELEASE_NULL(m_itemlist); m_controller = NULL; f_setcontroller(m_getEntile("chara_1")); //ITEMMANAGER设置控制器和镜头 f_setcamara(m_getEntile("chara_1")); ////////////////////////////////////////////////////////////////////////// //setTouchEnabled(true); this->scheduleUpdate(); //BattleMap的必要性初始化 CCTMXTiledMap* m_tilemap = (CCTMXTiledMap*) getChildByTag(kTagMap); CCTMXLayer* layer = m_tilemap->layerNamed("Battle"); CCDictionary* colordic; colordic = layer->getProperties(); c_r = 0;c_b = 0; c_y =0; c_r = colordic->valueForKey("red")->intValue(); c_b = colordic->valueForKey("blue")->intValue(); c_y = colordic->valueForKey("yellow")->intValue(); b_battle = 1; return true; }
bool CMGameMap::Init(CMReceiver* pReceiver,enumMarioLevel &eMarioLevel) { do { //初始化成员变量 m_fDropSpeedPlus = 0; m_fJumpSpeed = 0; m_bIsLeftKeyDown = false; m_bIsRightKeyDown = false; m_bIsJumpKeyDown = false; m_bIsFireKeyDown = false; m_bIsHeroDead = false; m_pReceiver = pReceiver; m_bNeedResetStage = false; //初始化游戏对象数组 m_pArrayItems = CCArray::create(); m_pArrayItems->retain(); m_pArrayMonsters = CCArray::create(); m_pArrayMonsters->retain(); m_pArrayBlocks = CCArray::create(); m_pArrayBlocks->retain(); m_pArrayFireBall = CCArray::create(); m_pArrayFireBall->retain(); //初始化Mario CMMario* pMario = CMMario::CreateHero(this,eMarioLevel); CC_BREAK_IF(pMario==NULL); pMario->setPosition(TileMapPosToTileMapLayerPos(ccp(2,11))); addChild(pMario,enZOrderFront,enTagMario); //pMario->SetStatus(enMarioStatusBig); //隐藏原落坑判断层 CCTMXLayer* pTrapLayer = layerNamed("trap"); CC_BREAK_IF(pTrapLayer==NULL); pTrapLayer->setVisible(false); //初始化显示金币 CCTMXLayer* pCoinLayer = layerNamed("coin"); CC_BREAK_IF(pCoinLayer==NULL); pCoinLayer->setVisible(false); //获得地图的瓦片数量 int nMapHorizontalTileNum = pCoinLayer->boundingBox().size.width/getTileSize().width; int nMapVerticalTileNum = pCoinLayer->boundingBox().size.height/getTileSize().height; //遍历每片瓦片,寻找金币,建立并加入金币集合 for (int i = 0;i<nMapHorizontalTileNum;i++) { for (int j = 0;j<nMapVerticalTileNum;j++) { if (TileMapPosToTileType(ccp(i,j))==enTileTypeCoin) { //将瓦片地图坐标转换为瓦片地图层坐标 CCPoint CoinTileMapLayerPos = TileMapPosToTileMapLayerPos(ccp(i,j)); CMItemCoin* pCoin = CMItemCoin::CreateItemIcon(CoinTileMapLayerPos,getTileSize(),pMario,this); if (pCoin==NULL) { CCLog("Coin init Error!"); } pCoin->setPosition(CoinTileMapLayerPos); pCoin->setAnchorPoint(ccp(0,0)); m_pArrayItems->addObject(pCoin); addChild(pCoin); } } } //初始化怪物显示 CCTMXObjectGroup* pObjectLayer = objectGroupNamed("objects"); CC_BREAK_IF(pObjectLayer==NULL); CCArray *ObjectArray = pObjectLayer->getObjects(); CCDictionary *pDic = NULL; for (unsigned int i = 0; i < ObjectArray->count(); i++) { pDic = (CCDictionary *)ObjectArray->objectAtIndex(i); int PosX = ((CCString*)pDic->objectForKey("x"))->intValue(); int PosY = ((CCString*)pDic->objectForKey("y"))->intValue(); PosY -= this->getTileSize().height; CCPoint TileXY = ccp(PosX, PosY); CCString *strName = (CCString*)pDic->objectForKey("name"); CCString *strType = (CCString*)pDic->objectForKey("type"); // 进行怪物的初始化,先根据名字来判断是不是enemy,再细分enemy类型 if (strName->m_sString == "enemy") { if (strType->m_sString == "mushroom") { CMMonsterMushrooms *pMonster = CMMonsterMushrooms::CreateMonsterMushrooms(TileXY,pMario,this,this); if (pMonster==NULL) { CCLog("pMonster==NULL!"); } pMonster->setPosition(ccp(TileXY.x,TileXY.y)); pMonster->setAnchorPoint(ccp(0,0)); m_pArrayMonsters->addObject(pMonster); addChild(pMonster,enZOrderFront); } if (strType->m_sString == "tortoise") { CMMonsterTortoise *pMonster = CMMonsterTortoise::CreateMonsterTortoise(TileXY,pMario,this,this); if (pMonster==NULL) { CCLog("pMonster==NULL!"); } pMonster->setPosition(ccp(TileXY.x,TileXY.y)); pMonster->setAnchorPoint(ccp(0,0)); m_pArrayMonsters->addObject(pMonster); addChild(pMonster,enZOrderFront); } if (strType->m_sString == "flower") { CMMonsterFlower *pMonster = CMMonsterFlower::CreateMonsterFlower(TileXY,pMario,this,this); if (pMonster==NULL) { CCLog("pMonster==NULL!"); } pMonster->setPosition(ccp(TileXY.x,TileXY.y)); pMonster->setAnchorPoint(ccp(0,0)); m_pArrayMonsters->addObject(pMonster); addChild(pMonster,enZOrderFront); } } } //初始化砖块显示 CCTMXLayer* pBlockLayer = layerNamed("block"); CC_BREAK_IF(pBlockLayer==NULL); pBlockLayer->setVisible(false); //获得地图的瓦片数量 // int nMapHorizontalTileNum = pCoinLayer->boundingBox().size.width/getTileSize().width; // int nMapVerticalTileNum = pCoinLayer->boundingBox().size.height/getTileSize().height; //遍历每片瓦片,寻找瓦片,建立并加入瓦片集合 for (int i = 0;i<nMapHorizontalTileNum;i++) { for (int j = 0;j<nMapVerticalTileNum;j++) { if (TileMapPosToTileType(ccp(i,j))==enTileTypeBlock) { //解析得到当前砖块的属性 int GID = pBlockLayer->tileGIDAt(ccp(i,j)); CCDictionary *pDic = propertiesForGID(GID); CC_BREAK_IF(pDic==NULL); CCString *strBlockType = (CCString*)pDic->objectForKey("blockType"); if (strBlockType==NULL) { continue; } int nBlockType = strBlockType->intValue(); //将瓦片地图坐标转换为瓦片地图层坐标 CCPoint BlockTileMapLayerPos = TileMapPosToTileMapLayerPos(ccp(i,j)); CMItemBlock* pBlock = CMItemBlock::CreateItemBlock(BlockTileMapLayerPos,getTileSize(),pMario,this,(enumBlockType)nBlockType); if (pBlock==NULL) { CCLog("Block init Error!"); } pBlock->setPosition(BlockTileMapLayerPos); pBlock->setAnchorPoint(ccp(0,0)); m_pArrayBlocks->addObject(pBlock); addChild(pBlock); } } } return true; } while (false); CCLog("Fun CMGameMap::Init Error!"); return false; }
// on "init" you need to initialize your instance bool HelloWorld::init() { bool bRet = false; do { ////////////////////////////////////////////////////////////////////////// // super init first ////////////////////////////////////////////////////////////////////////// CC_BREAK_IF(! CCLayer::init()); ////////////////////////////////////////////////////////////////////////// // add your codes below... ////////////////////////////////////////////////////////////////////////// CCSize size = CCDirector::sharedDirector()->getWinSize(); // 1. Add a menu item with "X" image, which is clicked to quit the program. // Create a "close" menu item with close icon, it's an auto release object. CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback)); CC_BREAK_IF(! pCloseItem); // Place the menu item bottom-right conner. pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20)); // Create a menu with the "close" menu item, it's an auto release object. CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); pMenu->setPosition(CCPointZero); CC_BREAK_IF(! pMenu); // Add the menu to HelloWorld layer as a child layer. this->addChild(pMenu, 1); //// 2. Add a label shows "Hello World". //// Create a label and initialize with string "Hello World". //CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24); //CC_BREAK_IF(! pLabel); //// Get window size and place the label upper. //pLabel->setPosition(ccp(size.width / 2, size.height - 50)); //// Add the label to HelloWorld layer as a child layer. //this->addChild(pLabel, 1); // 3. Add add a splash screen, show the cocos2d splash image. // pSprite = CCSprite::create("HelloWorld.png"); // CC_BREAK_IF(! pSprite); // pSprite->setPosition(ccp(size.width/3, size.height/3)); //pSprite->setAnchorPoint(ccp(0, 0)); // this->addChild(pSprite, 0); CCTMXTiledMap* tileMap = CCTMXTiledMap::tiledMapWithTMXFile("tmx/orthogonal.tmx"); this->addChild(tileMap, -1, TileMapNode); CCTMXLayer* eventLayer = tileMap->layerNamed("GameEventLayer"); eventLayer->setVisible(false); //tileMap->layerNamed("WinterLayer")->setVisible(false); //tileMap->layerNamed("Background")->setVisible(false); this->setTouchEnabled(true); bRet = true; } while (0); return bRet; }
bool Soko::MovePlayer(int dx, int dy) { // Only move if not a stationary move or a diagonal move if ( (dx!=0 && dy!=0) || (dx==0 && dy==0) ) return false; // Do some "collision detection" with the walls int oldX = mpPlayer->mpSprite->getPosition().x; int oldY = mpPlayer->mpSprite->getPosition().y; int oldCellX = oldX / 64; int oldCellY = oldY / 64; int mapYSize = this->getTileMap()->getMapSize().height; CCTMXLayer *pTMGround = this->getTileMap()->layerNamed("Ground"); // Allow for y coords of map being back to front int newX = oldCellX+dx; int newY = mapYSize - 1 - (oldCellY+dy); int tileGid = pTMGround->tileGIDAt(ccp(newX, newY ) ); if (tileGid == 1) // Trying to move into wall return false; // Now see if we're trying to push a box // - all box sprites have tag set to one CCSprite *pPushedBox = NULL; CCArray *pBoxes = this->getTileMap()->getChildren(); for(int i=0; i<pBoxes->count(); ++i) { CCSprite *pBox = (CCSprite *)pBoxes->objectAtIndex(i); if (pBox->getTag() == 1) { int boxXCell = (pBox->getPosition().x-32) / 64; int boxYCell = mapYSize - 1 - ((pBox->getPosition().y-32) / 64); if (boxXCell==newX && boxYCell==newY) { // We're walking into a box - see if we can push it int nextBoxXCell = boxXCell+dx; int nextBoxYCell = boxYCell+(dy*-1); // Need to reverse the direction int nextBoxTile = pTMGround->tileGIDAt( ccp(nextBoxXCell, nextBoxYCell) ); // - not if it is next to a wall if (nextBoxTile==1) return false; // See if it is next to another box - ie need to look to see if there is // a box in the cell we would be moving it to for(int j=0; j<pBoxes->count(); ++j) { CCSprite *pBox2 = (CCSprite *)pBoxes->objectAtIndex(j); if (pBox2->getTag() == 1) { int box2XCell = (pBox2->getPosition().x-32) / 64; int box2YCell = mapYSize - 1 - ((pBox2->getPosition().y-32) / 64); if (box2XCell == nextBoxXCell && box2YCell == nextBoxYCell) return false; } } // Push the box pPushedBox = pBox; } } } // Move the player (and box) and notify us when done ++mpPlayer->mMoveCount; mpPlayer->mIsMoving = true; // Need to see which way we've moved to see if we need to spin player to face movement direction int newFacing = 0; if (dx==-1) newFacing = 2; if (dy==1) newFacing = 3; if (dy==-1) newFacing = 1; // TODO minor bug - it should really take twice as long to rotate 180 degrees as // it does to rotate 90 CCFiniteTimeAction *playerRotateAction = NULL; float rotateDelay = 0.1f; if (newFacing != mpPlayer->mFacing) { playerRotateAction = CCRotateTo::actionWithDuration(rotateDelay, newFacing * 90); } else playerRotateAction = CCDelayTime::actionWithDuration(0.0f); // Slightly convoluted logic follows to get box to delay its move if player spins before // pushing. if (pPushedBox != NULL) { CCFiniteTimeAction *actionBoxMove = CCMoveTo::actionWithDuration( (ccTime)0.2, ccp(pPushedBox->getPosition().x+64*dx, pPushedBox->getPosition().y+64*dy) ); if (newFacing != mpPlayer->mFacing) pPushedBox->runAction( CCSequence::actions( CCDelayTime::actionWithDuration(rotateDelay), actionBoxMove, NULL) ); else pPushedBox->runAction( actionBoxMove ); ++mpPlayer->mPushCount; } CCFiniteTimeAction *actionMove = CCMoveTo::actionWithDuration( (ccTime)0.2, ccp(oldX+(dx*64), oldY+(dy*64)) ); CCFiniteTimeAction *actionMoveDone = CCCallFuncN::actionWithTarget( this, callfuncN_selector(Soko::spriteMoveFinished)); mpPlayer->mpSprite->runAction( CCSequence::actions(playerRotateAction, actionMove, actionMoveDone, NULL) ); mpPlayer->mFacing = newFacing; // Slightly heavier footstep if we're pushing if (pPushedBox == NULL) SimpleAudioEngine::sharedEngine()->playEffect( CCFileUtils::fullPathFromRelativePath("Soko_Footsteps01.wav") ); else SimpleAudioEngine::sharedEngine()->playEffect( CCFileUtils::fullPathFromRelativePath("Soko_Footsteps02.wav") ); return true; }
CCArray* LoadLevelEnemies::getEnemiesListFromLayer(CCTMXTiledMap *tilemap, Player *player) { CCTMXLayer* layer = tilemap->layerNamed("enemies"); CCSize layersize = layer->getLayerSize(); CCLOG("%s \n", "setEnemiesTilesInformation"); CCArray *enemieArray = CCArray::create(); CCDictionary* enemiesDictionary = PersistenceAux::getEnemyData(); CCLOG("Enemy data loaded"); for (int x = 0; x < layersize.width; x++) { for (int y = 0; y < layersize.height; y++) { unsigned int tmpgid = layer->tileGIDAt(ccp(x, y)); if (tmpgid != 0) { CCSprite* tile = layer->tileAt(ccp(x, y)); CCRect box = tile->boundingBox(); CCPoint boxsize = ccp(box.size.width, box.size.height); CCPoint tilePosition = ccpAdd(tile->getPosition(), ccpMult(boxsize, 0.5)); layer->removeTileAt(ccp(x, y)); // create the enemy directly CCDictionary* tileProperties = tilemap->propertiesForGID( tmpgid); CCLOG("%s \n", "dictionary for enemies properties"); CCString* enemyName = (CCString*) tileProperties->objectForKey( "name"); CCLOG("Enemy name %s \n", enemyName->getCString()); CCDictionary* enemyProperties = (CCDictionary *) enemiesDictionary->objectForKey( enemyName->getCString()); CCLOG("Enemy prop. Dictionary size %d \n", enemyProperties->count()); CCLOG("Enemy Position x %d \n", tilePosition.x); CCLOG("************** PLIST ****************** \n"); CCLOG("SPEED %s", ((CCString*) enemyProperties->objectForKey("speed"))->getCString()); CCLOG("JUMPFORCE %s", ((CCString*) enemyProperties->objectForKey("jump"))->getCString()); CCLOG("SIGHT %s", ((CCString*) enemyProperties->objectForKey("sight"))->getCString()); CCLOG("DIFICULT %s", ((CCString*) enemyProperties->objectForKey("dificult"))->getCString()); CCLOG("DEFAULT IMAGE %s", ((CCString*) enemyProperties->objectForKey( "defaultimage"))->getCString()); CCLOG("************** PLIST END ****************** \n"); MeeleEnemy* enemy = MeeleEnemy::create( (CCString*) enemyProperties->objectForKey( "defaultimage"), (CCString*) enemyProperties->objectForKey("dificult"), (CCString*) enemyProperties->objectForKey("jump"), (CCString*) enemyProperties->objectForKey("sight"), (CCString*) enemyProperties->objectForKey("speed"), tilePosition, enemyName, (CCString*) enemyProperties->objectForKey("damage") ); CCLOG("%s \n", "Initializing enemies"); enemy->initMeeleEnemy(player); CCLOG("%s \n", "Add enemies to enemy array"); enemieArray->addObject(enemy); } } } return enemieArray; }
void HelloWorld::ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent) { CCNode* node = this->getChildByTag(TileMapNode); //NSAssert([node isKindOfClass:[CCTMXTiledMap class]], @"not a CCTMXTiledMap"); CCTMXTiledMap* tileMap = (CCTMXTiledMap*)node; // get the position in tile coordinates from the touch location CCPoint touchLocation = this->locationFromTouch((cocos2d::CCTouch *)pTouches->anyObject()); CCPoint tilePos = this->tilePosFromLocation(touchLocation, tileMap); //// move tilemap so that touched tiles is at center of screen this->centerTileMapOnTileCoord(tilePos, tileMap); // Check if the touch was on water (eg. tiles with isWater property drawn in GameEventLayer) bool isTouchOnWater = false; CCTMXLayer* eventLayer = tileMap->layerNamed("GameEventLayer"); int tileGID = eventLayer->tileGIDAt(tilePos); // if (tileGID != 0) { CCDictionary* properties = tileMap->propertiesForGID(tileGID); if (properties) { //CCLOG(@"NSDictionary 'properties' contains:\n%@", properties); const CCString * isWaterProperty = properties->valueForKey("isWater"); isTouchOnWater = isWaterProperty->boolValue(); } } // Check if the touch was within one of the rectangle objects CCTMXObjectGroup* objectLayer = tileMap->objectGroupNamed("ObjectLayer"); //NSAssert([objectLayer isKindOfClass:[CCTMXObjectGroup class]], // @"ObjectLayer not found or not a CCTMXObjectGroup"); bool isTouchInRectangle = false; int numObjects = objectLayer->getObjects()->count(); for (int i = 0; i < numObjects; i++){ CCDictionary* properties = (CCDictionary*)objectLayer->getObjects()->objectAtIndex(i); CCRect rect = this->getRectFromObjectProperties(properties, tileMap); // if (CCRect::CCRectContainsPoint(rect, touchLocation)) { isTouchInRectangle = true; break; } } // decide what to do depending on where the touch was ... if (isTouchOnWater) { //[[SimpleAudioEngine sharedEngine] playEffect:@"alien-sfx.caf"]; CCLog("touchOnWater"); } else if (isTouchInRectangle) { CCLog("touchObject"); CCParticleSystem* system = CCParticleSystemQuad::particleWithFile("fx-explosion.plist"); system->setAutoRemoveOnFinish(true); system->setPosition(touchLocation); this->addChild(system, 1); } else { #if 0 // get the winter layer and toggle its visibility CCTMXLayer* winterLayer = tileMap->layerNamed("WinterLayer"); winterLayer->setVisible(!winterLayer->isVisible()); // other options you might be interested in are: // remove the touched tile winterLayer->removeTileAt(tilePos); // add a specific tile tileGID = winterLayer->tileGIDAt(CCPointMake(0, 19)); winterLayer->setTileGID(tileGID, tilePos); #endif } }