void SGPiecesCell::viewDidLoad() { ResourceManager::sharedInstance()->bindTexture("sgstorysectionlayer/sgstorysectionlayer.plist", RES_TYPE_LAYER_UI, m_tag); ResourceManager::sharedInstance()->bindTexture("sgpvpmainlayer/sgpvpmainlayer.plist", RES_TYPE_LAYER_UI, m_tag); ResourceManager::sharedInstance()->bindTexture("sgpieceslayer/sgpieceslayer.plist", RES_TYPE_LAYER_UI, m_tag); ResourceManager::sharedInstance()->bindTexture("sgcardslayer/sgcardslayer.plist", RES_TYPE_LAYER_UI, m_tag); ResourceManager::sharedInstance()->bindTexture("sgstrenglayer/sgstrenglayer.plist", RES_TYPE_LAYER_UI, m_tag, LIM_PNG_AS_PNG); char officerName[256] = "\0"; int shift = 0;// 名称黑色背景右向偏移 int iconId = -1; if (info->getItemType() == 0)//武将 { SGOfficerDataModel *temp = SGStaticDataManager::shareStatic()->getOfficerById(info->getCallCardId()); iconId = temp->getIconId(); } else if (info->getItemType() == 1)//装备 { SGEquipmentDataModel *temp =SGStaticDataManager::shareStatic()->getEquipById(info->getCallCardId()); iconId = temp->getIconId(); } SGMainManager::shareMain()->addHeadIconPlistByNum(iconId,sg_piecesLayer); sprintf(officerName, "head%d.png", iconId); shift = 10; //设置cell上的头像 CCSprite *piecesHead = CCSprite::createWithSpriteFrameName(officerName); piecesHead->setTag(HEAD_TAG); piecesHead->setPosition(ccp(-bgSize.width/2+ZoomInX(20), 2)); this->addChild(piecesHead); //品质框 SGPiecesDataModel *pieces = SGStaticDataManager::shareStatic()->getPiecesDictById(info->getItemId()); int starlvl = pieces->getStarLevel(); if (starlvl > 1) //策划表的蓝色为4,但是客户端的图形里标识为3,需要减1。 { starlvl -= 1; } char pinzhi[256] = "\0"; if (info->getItemType() == 0) { sprintf(pinzhi, "officerPinzhi_%d_0.png",starlvl); } else if (info->getItemType() == 1) { sprintf(pinzhi, "equipPinzhi_%d_0.png", starlvl); } CCSprite *pz = CCSprite::createWithSpriteFrameName(pinzhi); pz->setTag(PINZHI_TAG); this->addChild(pz); pz->setPosition(piecesHead->getPosition()); //头像蒙版 CCSprite *headMask = CCSprite::createWithSpriteFrameName("pieces_mask.png"); this->addChild(headMask); headMask->setPosition(piecesHead->getPosition()); int piecesCommonNum = 0; CCArray *piecesArray = SGPlayerInfo::sharePlayerInfo()->getPiecesCommonCards(); if (piecesArray->data && piecesArray->data->arr && piecesArray->count()) { piecesCommonNum = ((SGPiecesCard *)piecesArray->objectAtIndex(0))->getPiecesCurNum();//能使用的通用碎片 } CCSprite * bg = CCSprite::createWithSpriteFrameName("item_bigbg.png"); this->addChild(bg,-5); //名称黑色背景 CCSprite *namebg = CCSprite::createWithSpriteFrameName("name_bg.png"); namebg->setPosition(ccp(piecesHead->getPositionX() + piecesHead->getContentSize().width * 1.35 + shift, 20)); this->addChild(namebg, 0); //设置碎片名称 piecesName = SGCCLabelTTF::create(info->getPiecesName()->getCString(), FONT_BOXINFO, 25); piecesName->setAnchorPoint(ccp(0,0.5)); piecesName->setPosition(ccp(headMask->getPositionX() + headMask->getContentSize().width / 2 + 10, namebg->getPositionY())); this->addChild(piecesName, 1); totalAndCurProgress = SGCCLabelTTF::create(CCString::createWithFormat(str_PiecesCell_str4, info->getPiecesCurNum())->getCString(), FONT_BOXINFO, 23); totalAndCurProgress->setAnchorPoint(ccp(0, 0.5)); // totalAndCurProgress->setPosition(ccp(15 + prog->getPosition().x + prog->getContentSize().width, prog->getPosition().y)); totalAndCurProgress->setPosition(ccp( piecesName->getPosition().x , piecesName->getPositionY() - 25 )); this->addChild(totalAndCurProgress); // if (info->getPiecesCurNum() >= info->getSummonNeed())//拥有的碎片数能召唤 // { // totalAndCurProgress->setInsideColor(COLOR_GREEN); // } // else // { // totalAndCurProgress->setInsideColor(ccWHITE); // } }
bool GAFAsset::initWithImageData(const std::string& jsonPath) { if (!s3eFileCheckExists(jsonPath.c_str())) { GAFLOGERROR("CAN NOT create GAFAsset : %s does not exists", jsonPath.c_str()); return false; } GAFData aConfigData; //std::string fp = CCFileUtils::sharedFileUtils()->fullPathForFilename(jsonPath.c_str()); std::string fp = jsonPath; s3eFile * file = s3eFileOpen (fp.c_str(), "rb"); if (!file) { GAFLOGERROR("CAN NOT create GAFAsset : can not open %s.", fp.c_str()); return false; } aConfigData.setSize(s3eFileGetSize(file)); aConfigData.setBytes(new unsigned char[aConfigData.size()]); s3eFileRead(aConfigData.bytes(), aConfigData.size(), 1, file); s3eFileClose(file); aConfigData.setDeleteData(true); if (!aConfigData.bytes()) { GAFLOGERROR("Can not get data from json file : %s", jsonPath.c_str()); return NULL; } if (!aConfigData.bytes()) { GAFLOGWARN("can not init GAFAsset - invalid anImageData"); return false; } CCDictionary* configDictionary = CCJSONConverter::sharedConverter()->dictionaryFrom( (const char *)aConfigData.bytes()); CCString *versionNode = (CCString*)configDictionary->objectForKey(kVersionKey); if (!isAssetVersionPlayable(versionNode->getCString())) { return false; } CCArray *animationConfigFrames = (CCArray *)configDictionary->objectForKey(kAnimationConfigFramesKey); CCArray *interactionObjectNodes = (CCArray *)configDictionary->objectForKey(kInteractionObjectsKey); CCArray *standObjectsNodes = (CCArray *)configDictionary->objectForKey(kStandObjectsKey); CCArray *textureAtlasNode = (CCArray *)configDictionary->objectForKey(kTextureAtlasKey); CCArray *animationSequences = (CCArray *)configDictionary->objectForKey(kAnimationSequencesKey); CCDictionary *objectNodes = (CCDictionary *)configDictionary->objectForKey(kAnimationObjectsKey); CCDictionary *masksNodes = (CCDictionary *)configDictionary->objectForKey(kAnimationMasksKey); CCDictionary *namedPartsNodes = (CCDictionary *)configDictionary->objectForKey(kAnimationNamedPartsKey); if (!animationConfigFrames || !textureAtlasNode|| !objectNodes) { GAFLOGERROR("Error while creating GAFAsset. Required subnodes in dictionary are missing."); return false; } CC_SAFE_RELEASE(_textureAtlas); if (!textureAtlasNode->count()) { return false; } CCDictionary * atlasDictionary = (CCDictionary *)textureAtlasNode->objectAtIndex(0); float atlasScale = atlasScaleFromAtlasConfig(atlasDictionary); for (int i = 1; i < textureAtlasNode->count(); ++i) { CCDictionary * a = (CCDictionary *)textureAtlasNode->objectAtIndex(i); float as = atlasScaleFromAtlasConfig(a); if ( fabs(atlasScale - _currentDeviceScale) > fabs(as - _currentDeviceScale)) { atlasDictionary = a; atlasScale = as; } } _usedAtlasContentScaleFactor = atlasScale; CCArray * atlasesInfo = (CCArray *)atlasDictionary->objectForKey(kAtlasInfoKey); if (!atlasesInfo) { GAFLOGERROR("Error while creating GAFAsset.atlasesInfo subnode is missing in atlasDictionary."); return false; } _textureAtlas = GAFTextureAtlas::create(fp.c_str(), atlasDictionary); if (!_textureAtlas) { GAFLOGERROR("Failed to initialize GAFAsset. GAFTextureAtlas could not be created."); return false; } CC_SAFE_RETAIN(_textureAtlas); if (_objects != objectNodes) { CC_SAFE_RELEASE(_objects); _objects = objectNodes; CC_SAFE_RETAIN(_objects); } if (_masks != masksNodes) { CC_SAFE_RELEASE(_masks); _masks = masksNodes; CC_SAFE_RETAIN(_masks); } if (_namedParts != namedPartsNodes) { CC_SAFE_RELEASE(_namedParts); _namedParts = namedPartsNodes; CC_SAFE_RETAIN(_namedParts); } if (interactionObjectNodes) { CC_SAFE_RELEASE(_interactionObjects); _interactionObjects = CCArray::create(); CC_SAFE_RETAIN(_interactionObjects); for (unsigned int i = 0; i < interactionObjectNodes->count(); ++i) { CCDictionary * dict = (CCDictionary*)interactionObjectNodes->objectAtIndex(i); GAFInteractionObject * interObject = GAFInteractionObject::create(dict); if (interObject) { _interactionObjects->addObject(interObject); } } } if (standObjectsNodes) { CC_SAFE_RELEASE(_standObjects); _standObjects = CCArray::create(); CC_SAFE_RETAIN(_standObjects); for (unsigned int i = 0; i < standObjectsNodes->count(); ++i) { CCDictionary * dict = (CCDictionary*)standObjectsNodes->objectAtIndex(i); GAFActionObject * interObject = GAFActionObject::create(dict); if (interObject) { _standObjects->addObject(interObject); } } } loadFramesFromConfigDictionary(configDictionary); if (animationSequences) { loadAnimationSequences(animationSequences); } configDictionary->removeAllObjects(); return true; }
void PhysicsWorld::step(float deltaTime) { //TODO: /* how to clear out friction? currently, no friction */ Player* player = GlobalEngine::sharedGlobalEngine()->getPlayer(); CCArray* planets = GlobalEngine::sharedGlobalEngine()->getLevelMapLayer()->getPlanets(); //add gravity b2Vec2 force; force.SetZero(); b2Body* playerBody = player->getB2Body(); if (player->isGrounded() && player->getCurrentGround()->getType() == GameObjectTypePlanet) { //only apply gravity of current planet force = getGravity(player, (Planet*)player->getCurrentGround()); } else { for (int i = 0; i < planets->count(); i++) { force += getGravity(player, (Planet*)planets->objectAtIndex(i)); } } //rotate to gravity float angle = atan2(force.y, force.x) + b2_pi / 2.0f; playerBody->SetTransform(playerBody->GetPosition(), angle); playerBody->ApplyForceToCenter(force); //apply movement by force /*b2Vec2 localForce; switch (_player->getMoveState()) { case PlayerMoveStateLeft: localForce.Set(-PLAYER_MOVE_FORCE, 0); break; case PlayerMoveStateRight: localForce.Set(PLAYER_MOVE_FORCE, 0); break; default: localForce.SetZero(); break; } b2Rot rotation(angle); b2Vec2 globalForce = b2Mul(rotation, localForce); playerBody->ApplyForceToCenter(globalForce); //b2Vec2 impulse = globalSpeed - playerBody->GetLinearVelocity(); //impulse *= playerBody->GetMass(); //playerBody->ApplyLinearImpulse(impulse, playerBody->GetWorldCenter()); */ //apply movement by impulse if (player->isGrounded() && player->getJumpState() != PlayerJumpStateLeaving) { b2Vec2 localSpeed; switch (player->getMoveState()) { case PlayerMoveStateLeft: localSpeed.Set(-PLAYER_MOVE_SPEED, 0); break; case PlayerMoveStateRight: localSpeed.Set(PLAYER_MOVE_SPEED, 0); break; default: localSpeed.SetZero(); break; } b2Rot rotation(angle); b2Vec2 globalSpeed = b2Mul(rotation, localSpeed); b2Vec2 impulse = globalSpeed - playerBody->GetLinearVelocity(); impulse *= playerBody->GetMass(); playerBody->ApplyLinearImpulse(impulse, playerBody->GetWorldCenter()); } //apply jumping if (player->getJumpState() == PlayerJumpStatePending) { player->setJumpState(PlayerJumpStateLeaving); if (player->isGrounded()) { b2Vec2 localJumpSpeed; localJumpSpeed.Set(PLAYER_JUMP_SPEED, 0); b2Rot jumpRotation(angle + b2_pi / 2.0f); b2Vec2 globalJumpSpeed = b2Mul(jumpRotation, localJumpSpeed); b2Vec2 jumpImpulse = globalJumpSpeed; jumpImpulse *= playerBody->GetMass(); playerBody->ApplyLinearImpulse(jumpImpulse, playerBody->GetWorldCenter()); } } //check damping if (player->isGrounded()) { playerBody->SetLinearDamping(0); } else { playerBody->SetLinearDamping(PLAYER_DAMPING); } _world->Step(deltaTime, VELOCITY_ITERATIONS, POSITION_ITERATIONS); }
//滑动时更新cell void SGPiecesCell::updatePiecesCard(SGPiecesCard *card) { ResourceManager::sharedInstance()->bindTexture("sgpieceslayer/sgpieceslayer.plist", RES_TYPE_LAYER_UI, sg_piecesLayer); char officerName[256] = "\0"; int shift = 0;// 名称黑色背景右向偏移 int iconId = -1; if (card->getItemType() == 0)//武将 { SGOfficerDataModel *temp = SGStaticDataManager::shareStatic()->getOfficerById(card->getCallCardId()); iconId = temp->getIconId(); } else if (card->getItemType() == 1)//装备 { SGEquipmentDataModel *temp =SGStaticDataManager::shareStatic()->getEquipById(card->getCallCardId()); iconId = temp->getIconId(); } SGMainManager::shareMain()->addHeadIconPlistByNum(iconId,sg_piecesLayer); sprintf(officerName, "head%d.png", iconId); shift = 10; //滑动过后重置cell上的头像 CCSprite *piecesHeadTemp = CCSprite::createWithSpriteFrameName(officerName); static_cast<CCSprite *>(this->getChildByTag(HEAD_TAG))->setDisplayFrame(piecesHeadTemp->displayFrame()); //滑动过后的品质框 char pinzhi[256] = "\0"; if (card->getItemType() == 0) { SGOfficerDataModel *temp = SGStaticDataManager::shareStatic()->getOfficerById(card->getCallCardId()); int starlvl = temp->getOfficerCurrStarLevel(); if (starlvl>1) { starlvl-=1; } sprintf(pinzhi, "officerPinzhi_%d_0.png",starlvl); } else if (card->getItemType() == 1) { SGEquipmentDataModel *equipModel = SGStaticDataManager::shareStatic()->getEquipById(info->getCallCardId()); sprintf(pinzhi, "equipPinzhi_%d_0.png", equipModel->getEquipStarPinzhi()); } //更新的时候重围品质框 CCSprite *pzTemp = CCSprite::createWithSpriteFrameName(pinzhi); static_cast<CCSprite *>(this->getChildByTag(PINZHI_TAG))->setDisplayFrame(pzTemp->displayFrame()); //头像蒙版不需要更新 int addCommonPieces = 0;//加到当前碎片数上,值由isUseCommon来决定是0,还是可使用的通用碎片数 int piecesCommonNum = 0; CCArray *piecesArray = SGPlayerInfo::sharePlayerInfo()->getPiecesCommonCards(); if (piecesArray->data && piecesArray->data->arr && piecesArray->count()) { piecesCommonNum = ((SGPiecesCard *)piecesArray->objectAtIndex(0))->getPiecesCurNum();//能使用的通用碎片 } //重置碎片名称 piecesName->setString(card->getPiecesName()->getCString()); //更新显示进度 totalAndCurProgress->setString(CCString::createWithFormat(str_PiecesCell_str4, card->getPiecesCurNum())->getCString()); // if (card->getPiecesCurNum() >= card->getSummonNeed())//拥有的碎片数能召唤 // { // totalAndCurProgress->setInsideColor(COLOR_GREEN); // } // else // { // totalAndCurProgress->setInsideColor(ccWHITE); // } }
void CFrontground::GetMapInfo() { if ( m_pCrashRectArray ) m_pCrashRectArray->release(); m_pCrashRectArray = m_pTileMap->objectGroupNamed("pengzhuang")->getObjects(); m_pCrashRectArray->retain(); if ( m_pCrashTriaArray ) m_pCrashTriaArray->release(); m_pCrashTriaArray = m_pTileMap->objectGroupNamed("zuobiao3")->getObjects(); m_pCrashTriaArray->retain(); if ( m_unLevel < 49 ) m_pTileMap->reorderChild((CCSpriteBatchNode*)m_pTileMap->getChildren()->objectAtIndex(3),5); else if ( m_unLevel < 55 ) { m_pTileMap->reorderChild((CCSpriteBatchNode*)m_pTileMap->getChildren()->objectAtIndex(1),0); m_pTileMap->reorderChild((CCSpriteBatchNode*)m_pTileMap->getChildren()->objectAtIndex(2),1); m_pTileMap->reorderChild((CCSpriteBatchNode*)m_pTileMap->getChildren()->objectAtIndex(3),1); m_pTileMap->reorderChild((CCSpriteBatchNode*)m_pTileMap->getChildren()->objectAtIndex(4),2); m_pTileMap->reorderChild((CCSpriteBatchNode*)m_pTileMap->getChildren()->objectAtIndex(5),2); m_pTileMap->reorderChild((CCSpriteBatchNode*)m_pTileMap->getChildren()->objectAtIndex(6),5); m_pTileMap->reorderChild((CCSpriteBatchNode*)m_pTileMap->getChildren()->objectAtIndex(7),5); } if ( m_pObjectArray ) { delete[] m_pObjectArray; m_pObjectArray = NULL; } CCArray* pObjectArray = m_pTileMap->objectGroupNamed("zuobiao1")->getObjects(); m_unObjectArrayNum = pObjectArray->count(); if ( m_unObjectArrayNum ) { m_pObjectArray = new MapObject[m_unObjectArrayNum]; for ( int i = 0; i < m_unObjectArrayNum; i++ ) { CCDictionary* pObject = (CCDictionary*)pObjectArray->objectAtIndex(i); int kind = pObject->valueForKey("id")->uintValue(); m_pObjectArray[i].unKind = kind; m_pObjectArray[i].x = pObject->valueForKey("x")->floatValue(); m_pObjectArray[i].y = pObject->valueForKey("y")->floatValue(); switch ( kind ) { case 0: m_pObjectArray[i].iToward = pObject->valueForKey("type")->uintValue(); m_pObjectArray[i].argi1 = pObject->valueForKey("index")->intValue(); m_pObjectArray[i].argi2 = pObject->valueForKey("add")->intValue(); m_pObjectArray[i].argi3 = pObject->valueForKey("num")->intValue(); m_pObjectArray[i].w = 170; m_pObjectArray[i].h = 800; m_pObjectArray[i].argb = false; m_pObjectArray[i].argb1 = false; m_pObjectArray[i].bCheck= false; break; case 1: m_pObjectArray[i].sPath = g_sBoxPath[pObject->valueForKey("type")->uintValue()]; m_pObjectArray[i].arg1 = 0; if ( m_unLevel < 0 ) m_pObjectArray[i].argi3 = pObject->valueForKey("item")->intValue(); break; case 2: m_pObjectArray[i].sPath = g_sStairPath[pObject->valueForKey("type")->uintValue()-1]; m_pObjectArray[i].argi1 = pObject->valueForKey("type")->uintValue() - 1; m_pObjectArray[i].arg1 = m_pObjectArray[i].x; m_pObjectArray[i].arg2 = pObject->valueForKey("max")->floatValue(); m_pObjectArray[i].arg3 = 2.0; m_pObjectArray[i].bCheck= true; break; case 3: m_pObjectArray[i].sPath = g_sStairPath[pObject->valueForKey("type")->uintValue()-1]; m_pObjectArray[i].argi1 = pObject->valueForKey("type")->uintValue() - 1; m_pObjectArray[i].arg1 = m_pObjectArray[i].y; m_pObjectArray[i].arg2 = pObject->valueForKey("max")->floatValue(); m_pObjectArray[i].arg3 = 2.0; m_pObjectArray[i].bCheck= true; break; case 4: m_pObjectArray[i].sPath = "Tile/a3.png"; m_pObjectArray[i].argi1 = 0; m_pObjectArray[i].argb = false; m_pObjectArray[i].bCheck= true; break; case 5: m_pObjectArray[i].sPath = "Tile/a4.png"; m_pObjectArray[i].argi1 = 0; break; case 6: m_pObjectArray[i].sPath = g_sStairPath[pObject->valueForKey("type")->uintValue()-1]; m_pObjectArray[i].argi1 = pObject->valueForKey("type")->uintValue() - 1; m_pObjectArray[i].arg1 = m_pObjectArray[i].x; m_pObjectArray[i].arg2 = pObject->valueForKey("to")->floatValue(); m_pObjectArray[i].arg3 = 2.0; m_pObjectArray[i].bCheck= true; if ( m_pObjectArray[i].arg2 == 0.0 ) m_pObjectArray[i].iToward = 1; else m_pObjectArray[i].iToward = -1; break; case 7: m_pObjectArray[i].argi1 = pObject->valueForKey("type")->intValue(); m_pObjectArray[i].argi2 = 0; m_pObjectArray[i].arg1 = pObject->valueForKey("max")->floatValue(); m_pObjectArray[i].arg2 = m_pObjectArray[i].y; break; case 8: m_pObjectArray[i].argi2 = 0; m_pObjectArray[i].argb = false; break; case 9: m_pObjectArray[i].argi1 = pObject->valueForKey("type")->intValue(); m_pObjectArray[i].argi2 = 0; m_pObjectArray[i].arg1 = 200; m_pObjectArray[i].argb = true; m_pObjectArray[i].w = 100; m_pObjectArray[i].h = 40; m_pObjectArray[i].bCheck= true; break; case 10: m_pObjectArray[i].argi1 = pObject->valueForKey("type")->intValue(); m_pObjectArray[i].argi2 = 249; m_pObjectArray[i].argb = true; m_pObjectArray[i].w = 500; m_pObjectArray[i].h = 800; m_pObjectArray[i].bCheck= true; break; case 11: m_pObjectArray[i].argi1 = pObject->valueForKey("type")->intValue(); m_pObjectArray[i].argi2 = pObject->valueForKey("max")->intValue(); m_pObjectArray[i].argb = false; m_pObjectArray[i].bCheck= true; switch ( m_pObjectArray[i].argi1 ) { case 0: m_pObjectArray[i].w = 130; m_pObjectArray[i].h = 111; break; case 1: m_pObjectArray[i].w = 344; m_pObjectArray[i].h = 170; break; } break; case 12: m_pObjectArray[i].argi3 = 0; break; case 13: m_pObjectArray[i].arg1 = 0.0f; m_pObjectArray[i].argi1 = 0; m_pObjectArray[i].w = 117; m_pObjectArray[i].h = 63; m_pObjectArray[i].bCheck= true; break; case 14: m_pObjectArray[i].argb = true; m_pObjectArray[i].w = 49; m_pObjectArray[i].h = 80; break; case 15: m_pObjectArray[i].argb = true; m_pObjectArray[i].argi1 = pObject->valueForKey("index")->intValue(); m_pObjectArray[i].w = 20; m_pObjectArray[i].h = 20; break; case 16: m_pObjectArray[i].argb = true; m_pObjectArray[i].w = 100; m_pObjectArray[i].h = 200; m_pObjectArray[i].bCheck= true; break; case 17: m_pObjectArray[i].w = 10; m_pObjectArray[i].h = 10; break; case 18: m_pObjectArray[i].w = 56; m_pObjectArray[i].h = 42; break; case 19: m_pObjectArray[i].w = pObject->valueForKey("width")->intValue(); m_pObjectArray[i].h = pObject->valueForKey("height")->intValue(); break; } if ( m_pObjectArray[i].sPath != "" ) { CCSprite* pSprite = new CCSprite; pSprite->initWithFile(m_pObjectArray[i].sPath.c_str()); CCSize size = pSprite->getContentSize(); m_pObjectArray[i].w = size.width; m_pObjectArray[i].h = size.height - 24; delete pSprite; } } } if ( m_pMonsterArray ) { m_pMonsterArray->release(); VECTORCLEAN(m_vecObjectArray, MonsterObject); m_vecObjectArray.clear(); } m_pMonsterArray = m_pTileMap->objectGroupNamed("zuobiao2")->getObjects(); m_pMonsterArray->retain(); if ( m_pMonsterArray->count() ) { if ( CGameControler::GetGameControler()->m_iLevelType != 2 ) { for ( unsigned int i = 0; i < m_pMonsterArray->count(); i++ ) { CCDictionary* pObject = (CCDictionary*)m_pMonsterArray->objectAtIndex(i); int id = pObject->valueForKey("id")->uintValue()%100 - 1 + (pObject->valueForKey("id")->uintValue()/100-1)*25; #ifdef GameTypeC if ( id == 4 || id == 6 ) continue; if ( id != 5 && id != 8 ) id = id%2; #endif MonsterObject* pMonsterInfo = new MonsterObject; pMonsterInfo->kind = id; pMonsterInfo->x = pObject->valueForKey("x")->floatValue(); pMonsterInfo->y = pObject->valueForKey("y")->floatValue(); pMonsterInfo->time = pObject->valueForKey("time")->uintValue()*50; pMonsterInfo->num = pObject->valueForKey("num")->intValue(); pMonsterInfo->index = pObject->valueForKey("z")->intValue(); if ( pMonsterInfo->kind == 4 ) { pMonsterInfo->dist = pObject->valueForKey("dist")->floatValue(); } if ( pMonsterInfo->num ) { pMonsterInfo->range = pObject->valueForKey("range")->intValue(); pMonsterInfo->timemax = pObject->valueForKey("timemax")->intValue(); pMonsterInfo->timemin = pObject->valueForKey("timmin")->intValue(); } else pMonsterInfo->range = 0; m_vecObjectArray.push_back(pMonsterInfo); } } } }
void SGGeneralsLayer::initMsg() { SGCardItem::addCardItemRes(sg_generalsLayer);//添加item资源 // tableViewColumns = 5; tableViewHeight = 120; _allData = CCArray::create(); _allData->retain(); CCArray *array =CCArray::create(); array->retain(); array =SGPlayerInfo::sharePlayerInfo()->getOfficerCards(); ; for (int i=0;i<6;i++) { stars[i]=0; } for(int i=0;i<array->count();i++)//统计素材每个星级的数量 { SGBaseMilitaryCard *baseMilitaryCard = (SGBaseMilitaryCard *)array->objectAtIndex(i); // CCString *str_ = CCString::create(baseMilitaryCard->getClassName()); // if (str_->isEqual(CCString::create("SGOfficerCard"))) // { SGOfficerCard *card = (SGOfficerCard *)baseMilitaryCard; int po1 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(1,card); int po2 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(2,card); int po3 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(3,card); if ( po1 == 0 && po2 ==0 && po3 == 0 && card->getIsProt() == 0) { int s = card->getCurrStar()-1; stars[s]+=1; } // } } for(int i=0;i<array->count();i++) { if (enterType==4) {//首页-强化-主将计 SGSkillDataModel *lordSkill = SGStaticDataManager::shareStatic()->getLordSkillById(((SGOfficerCard *)array->objectAtIndex(i))->getLordId()); if(lordSkill && lordSkill->getNextId() && ((SGOfficerCard *)array->objectAtIndex(i))->getLordMaxLevel()>lordSkill->getLevel()) _allData->addObject(array->objectAtIndex(i)); } else if (enterType==5)//首页-强化-武将计 { SGSkillDataModel *officerSkill = SGStaticDataManager::shareStatic()->getGeneralSkillById(((SGOfficerCard *)array->objectAtIndex(i))->getOfficerSkil()); if (officerSkill && officerSkill->getNextId() && ((SGOfficerCard *)array->objectAtIndex(i))->getSkillMaxLevel()>officerSkill->getSkillMaxLevel()) { _allData->addObject(array->objectAtIndex(i)); } } else if (enterType ==2)//首页-强化按键-强化武将 { if (((SGOfficerCard *)array->objectAtIndex(i))->getCurrLevel() < ((SGOfficerCard *)array->objectAtIndex(i))->getMaxLevel()) { _allData->addObject(array->objectAtIndex(i)); } } else if(enterType == 3)//首页-转生-武将 { SGOfficerCard *card = (SGOfficerCard *)array->objectAtIndex(i); int usednum = 0; if (card->getMaxStar()) { if (card->getCurrStar()>=1) { CCArray* array =SGPlayerInfo::sharePlayerInfo()->getOfficerCards(); for(int i=0;i<array->count();i++) { SGBaseMilitaryCard *baseMilitaryCard = (SGBaseMilitaryCard *)array->objectAtIndex(i); SGOfficerCard *card1 = (SGOfficerCard *)baseMilitaryCard; int po1 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(1,card1); int po2 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(2,card1); int po3 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(3,card1); if ( po1 == 0 && po2 ==0 && po3 == 0 && card1->getIsProt() == 0 && card1->getSsid()!=card->getSsid() && card1->getProtoId() ==((SGOfficerCard*)card)->getProtoId() && card->getCurrStar() == card1->getCurrStar()) { usednum++; } } } else { int star = card->getCurrStar()-1; bool po = !(SGTeamgroup::shareTeamgroupInfo()->isOnEmbattle((SGOfficerCard*)card)); usednum = stars[star]-(int)po; } card->setAdvanceStuffNum(usednum); _allData->addObject(card); } } else { SGOfficerCard *card = (SGOfficerCard *)array->objectAtIndex(i); int usednum = 0; if (card->getMaxStar()) { if (card->getCurrStar()>=1) { CCArray* array =SGPlayerInfo::sharePlayerInfo()->getOfficerCards(); for(int i=0;i<array->count();i++) { SGBaseMilitaryCard *baseMilitaryCard = (SGBaseMilitaryCard *)array->objectAtIndex(i); SGOfficerCard *card1 = (SGOfficerCard *)baseMilitaryCard; int po1 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(1,card1); int po2 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(2,card1); int po3 = SGTeamgroup::shareTeamgroupInfo()->getPositionId(3,card1); if ( po1 == 0 && po2 ==0 && po3 == 0 && card1->getIsProt() == 0 && card1->getSsid()!=card->getSsid() && card1->getProtoId() ==((SGOfficerCard*)card)->getProtoId() && card->getCurrStar() == card1->getCurrStar()) { usednum+=1; if(usednum>3) break; } // } } } else { int star = card->getCurrStar()-1; bool po = !(SGTeamgroup::shareTeamgroupInfo()->isOnEmbattle((SGOfficerCard*)card)); usednum = stars[star]-(int)po; } card->setAdvanceStuffNum(usednum); } //SGSkillDataModel *lordSkill = SGStaticDataManager::shareStatic()->getLordSkillById(((SGOfficerCard *)array->objectAtIndex(i))->getLordId()); // if ((lordSkill && lordSkill->getNextId() &&)|| lordSkill ==NULL) //如果不是小于等于,新手引导完,对应的武将就不见了,因为10级不小于10级,这个人就被加入武将列表了 //if (((SGOfficerCard *)array->objectAtIndex(i))->getCurrLevel() <= ((SGOfficerCard *)array->objectAtIndex(i))->getMaxLevel()) //{ _allData->addObject(array->objectAtIndex(i)); //} //else if(lordSkill && lordSkill->getNextId() && lordSkill->getLevel() < ((SGOfficerCard *)array->objectAtIndex(i))->getLordMaxLevel()) //{ // _allData->addObject(array->objectAtIndex(i)); //} } } //_allData->retain(); CCArray *offices = SGPlayerInfo::sharePlayerInfo()->getPropCards(); //4.从强化主将计进入5.强化被动技进入 if (enterType ==2 ||enterType ==3 ||enterType==4 ||enterType==5) { } else { CCObject *obj_ = NULL; CCARRAY_FOREACH(offices, obj_) { SGPropsCard *card = (SGPropsCard *)obj_; if (card && card->getType() == 1) { _allData->addObject(card); } } }
void RPGBattleMenu::onMenu(cocos2d::CCObject *pObject) { CCMenuItem *menuItem = (CCMenuItem*)pObject; SimpleAudioEngine::sharedEngine()->playEffect("audio_effect_btn.wav"); switch (menuItem->getTag()) { case kRPGBattleMenuTagSkill: { CCLog("技能"); this->hideMenu(); this->m_selectedMenuTag = kRPGBattleMenuTagSkill; CCMenuItemSprite *menuCancel = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("commons_btn_back_04.png"), CCSprite::createWithSpriteFrameName("commons_btn_back_04.png"), this, menu_selector(RPGBattleMenu::onMenu)); menuCancel->setPosition(ccp(43, 596)); menuCancel->setTag(kRPGBattleMenuTagCancel); menuCancel->setScale(0.75); this->addChild(menuCancel); CCTMXTiledMap *selectLayer = CCTMXTiledMap::create(CCString::createWithFormat("battle_select_%s.tmx", CCUserDefault::sharedUserDefault()->getStringForKey(GAME_STYLE).c_str())->getCString()); selectLayer->setPosition(ccp((CCDirector::sharedDirector()->getWinSize().width - selectLayer->getContentSize().width) / 2, (CCDirector::sharedDirector()->getWinSize().height - selectLayer->getContentSize().height) / 2)); selectLayer->setTag(kRPGBattleSceneLayerTagSkillSelectDialog); ((RPGBattleSceneLayer*)this->m_parentNode)->addChild(selectLayer); ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(true); //显示title和分隔线 addLab(selectLayer, 199, (CCString*)this->m_stringList->objectForKey("skill_title"), 25, ccp(310, 285)); CCLabelTTF *titleLab = (CCLabelTTF*)selectLayer->getChildByTag(199); titleLab->setFontFillColor(ccc3(144, 144, 144)); CCSprite *separate = CCSprite::createWithSpriteFrameName("separate.png"); separate->setPosition(ccp(selectLayer->getContentSize().width / 2, 260)); separate->setScaleX(0.65); separate->setTag(198); selectLayer->addChild(separate); //加载技能数据 CCTableView *tableView = (CCTableView*)selectLayer->getChildByTag(197); if(!tableView) { tableView = CCTableView::create(this, ccp(selectLayer->getContentSize().width, selectLayer->getContentSize().height - 80)); tableView->setDirection(kCCScrollViewDirectionVertical); tableView->setPosition(CCSizeZero); tableView->setDelegate(this); tableView->setVerticalFillOrder(kCCTableViewFillTopDown); tableView->setTag(197); selectLayer->addChild(tableView); } this->m_tableItems->removeAllObjects(); string wq = ""; JsonBox::Value json; json.loadFromString(this->m_playerData->m_skill.c_str()); JsonBox::Array jsonArr = json.getArray(); for (int i = 0; i < jsonArr.size(); i++) { char* str = (char*)malloc(10 * sizeof(char)); OzgCCUtility::itoa(jsonArr[i].getInt(), str); wq.append(str); if(i + 1 < jsonArr.size()) wq.append(", "); free(str); } if((int)wq.length() > 0) { CppSQLite3Query query = this->m_db->execQuery(CCString::createWithFormat(SKILL_QUERY, wq.c_str())->getCString()); while(!query.eof()) { RPGSkillBtnData *skill = RPGSkillBtnData::create(); skill->m_dataId = query.getIntField("id"); skill->m_name = query.getStringField("name_cns"); skill->m_MP = query.getIntField("mp"); skill->m_skillAttack = query.getIntField("skill_attack"); skill->m_type = query.getIntField("type"); skill->m_attr = query.getIntField("attr"); skill->m_enabled = true; //不能使用技能的情况 if(this->m_playerData->m_MP <= 0 || this->m_playerData->m_HP <= 0) skill->m_enabled = false; else if(this->m_playerData->m_MP < skill->m_MP) skill->m_enabled = false; this->m_tableItems->addObject(skill); query.nextRow(); } query.finalize(); } tableView->reloadData(); //加载技能数据 end ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(false); } break; case kRPGBattleMenuTagItems: { CCLog("道具"); this->hideMenu(); this->m_selectedMenuTag = kRPGBattleMenuTagItems; CCMenuItemSprite *menuCancel = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("commons_btn_back_04.png"), CCSprite::createWithSpriteFrameName("commons_btn_back_04.png"), this, menu_selector(RPGBattleMenu::onMenu)); menuCancel->setPosition(ccp(43, 596)); menuCancel->setTag(kRPGBattleMenuTagCancel); menuCancel->setScale(0.75); this->addChild(menuCancel); CCTMXTiledMap *selectLayer = CCTMXTiledMap::create(CCString::createWithFormat("battle_select_%s.tmx", CCUserDefault::sharedUserDefault()->getStringForKey(GAME_STYLE).c_str())->getCString()); selectLayer->setPosition(ccp((CCDirector::sharedDirector()->getWinSize().width - selectLayer->getContentSize().width) / 2, (CCDirector::sharedDirector()->getWinSize().height - selectLayer->getContentSize().height) / 2)); selectLayer->setTag(kRPGBattleSceneLayerTagItemsSelectDialog); ((RPGBattleSceneLayer*)this->m_parentNode)->addChild(selectLayer); ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(true); //显示title和分隔线 addLab(selectLayer, 199, (CCString*)this->m_stringList->objectForKey("items_title"), 25, ccp(310, 285)); CCLabelTTF *titleLab = (CCLabelTTF*)selectLayer->getChildByTag(199); titleLab->setFontFillColor(ccc3(144, 144, 144)); CCSprite *separate = CCSprite::createWithSpriteFrameName("separate.png"); separate->setPosition(ccp(selectLayer->getContentSize().width / 2, 260)); separate->setScaleX(0.65); separate->setTag(198); selectLayer->addChild(separate); //加载道具数据 CCTableView *tableView = (CCTableView*)selectLayer->getChildByTag(197); if(!tableView) { tableView = CCTableView::create(this, ccp(selectLayer->getContentSize().width, selectLayer->getContentSize().height - 80)); tableView->setDirection(kCCScrollViewDirectionVertical); tableView->setPosition(CCSizeZero); tableView->setDelegate(this); tableView->setVerticalFillOrder(kCCTableViewFillTopDown); tableView->setTag(197); selectLayer->addChild(tableView); } this->m_tableItems->removeAllObjects(); CCArray *existingItems = ((RPGBattleSceneLayer*)this->m_parentNode)->m_existingItems; for (int i = 0; i < existingItems->count(); i++) this->m_tableItems->addObject(existingItems->objectAtIndex(i)); tableView->reloadData(); //加载道具数据 end ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(false); } break; case kRPGBattleMenuTagEscape: { // CCLog("逃跑"); float success = CCRANDOM_0_1(); if(success >= 0.0 && success <= 0.5) { // CCLog("逃跑成功"); this->setEnabled(false); this->removeFromParentAndCleanup(true); ((RPGBattleSceneLayer*)this->m_parentNode)->goToMap(); } else { ((RPGBattleSceneLayer*)this->m_parentNode)->showMsg((CCString*)this->m_stringList->objectForKey("escape_fail")); //重置进度条 this->m_playerData->m_progress = 0.0; CCProgressTimer *battleProgress = (CCProgressTimer*)this->m_parentNode->getChildByTag(kRPGBattleSceneLayerTagPlayerProgress + this->m_playerData->m_dataId); battleProgress->setPercentage(this->m_playerData->m_progress); ((RPGBattleSceneLayer*)this->m_parentNode)->scheduleUpdate(); CCTMXTiledMap *bgLayer = (CCTMXTiledMap*)this->m_parentNode->getChildByTag(kRPGBattleMenuTagBg); bgLayer->removeFromParentAndCleanup(true); this->removeFromParentAndCleanup(true); } } break; case kRPGBattleMenuTagCancel: { // CCLog("取消"); this->showMenu(); CCMenuItem *menuCancel = (CCMenuItem*)this->getChildByTag(kRPGBattleMenuTagCancel); menuCancel->removeFromParentAndCleanup(true); switch (this->m_selectedMenuTag) { case kRPGBattleMenuTagAttack: CCLog("取消攻击"); ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(false); ((RPGBattleSceneLayer*)this->m_parentNode)->cancelAllSelected(); break; case kRPGBattleMenuTagSkill: CCLog("取消技能列表"); if(((RPGBattleSceneLayer*)this->m_parentNode)->getChildByTag(kRPGBattleSceneLayerTagSkillSelectDialog)) ((RPGBattleSceneLayer*)this->m_parentNode)->removeChildByTag(kRPGBattleSceneLayerTagSkillSelectDialog, true); ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(false); ((RPGBattleSceneLayer*)this->m_parentNode)->cancelAllSelected(); break; case kRPGBattleMenuTagItems: CCLog("取消道具列表"); if(((RPGBattleSceneLayer*)this->m_parentNode)->getChildByTag(kRPGBattleSceneLayerTagItemsSelectDialog)) ((RPGBattleSceneLayer*)this->m_parentNode)->removeChildByTag(kRPGBattleSceneLayerTagItemsSelectDialog, true); ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(false); ((RPGBattleSceneLayer*)this->m_parentNode)->cancelAllSelected(); break; // default: // break; } } break; case kRPGBattleMenuTagCancel2: { //这个选择了一个技能或道具后,到了选择目标对象的一步,使用到的取消按钮 CCMenuItemSprite *menuCancel = (CCMenuItemSprite*)this->getChildByTag(kRPGBattleMenuTagCancel); menuCancel->setVisible(true); CCMenuItemSprite *menuCancel2 = (CCMenuItemSprite*)this->getChildByTag(kRPGBattleMenuTagCancel2); menuCancel2->removeFromParentAndCleanup(true); if(this->m_parentNode->getChildByTag(kRPGBattleSceneLayerTagItemsSelectDialog)) this->m_parentNode->getChildByTag(kRPGBattleSceneLayerTagItemsSelectDialog)->setVisible(true); if(this->m_parentNode->getChildByTag(kRPGBattleSceneLayerTagSkillSelectDialog)) this->m_parentNode->getChildByTag(kRPGBattleSceneLayerTagSkillSelectDialog)->setVisible(true); ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(false); ((RPGBattleSceneLayer*)this->m_parentNode)->cancelAllSelected(); } break; default: { CCLog("攻击"); this->hideMenu(); this->m_selectedMenuTag = kRPGBattleMenuTagAttack; CCMenuItemSprite *menuCancel = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("commons_btn_back_04.png"), CCSprite::createWithSpriteFrameName("commons_btn_back_04.png"), this, menu_selector(RPGBattleMenu::onMenu)); menuCancel->setPosition(ccp(43, 596)); menuCancel->setTag(kRPGBattleMenuTagCancel); menuCancel->setScale(0.75); this->addChild(menuCancel); ((RPGBattleSceneLayer*)this->m_parentNode)->enabledTouched(true); } break; } }
MapNode* MapUtils::searchPath(int startRowIndex, int startColIndex, int endRowIndex, int endColIndex, Map* map) { CCArray* openList = new CCArray; CCArray* closeList = new CCArray; MapNode* endNode = map->getMapNode(endRowIndex, endColIndex); MapNode* searchNode = map->getMapNode(startRowIndex, startColIndex); searchNode->g = 0; searchNode->h = MapUtils::calculateH(searchNode, endNode); searchNode->f = searchNode->g + searchNode->h; int g, f, h; const int NORMAL = 10; const int ANGLE = 14; while (searchNode->nodeData->matrixIndex->rowIndex != endRowIndex || searchNode->nodeData->matrixIndex->colIndex != endColIndex) { /***遍历点的四周****/ int colIndex, rowIndex, col, row, i, j; row = std::min(searchNode->nodeData->matrixIndex->rowIndex + 2, map->nodeData->matrix->row); col = std::min(searchNode->nodeData->matrixIndex->colIndex + 2, map->nodeData->matrix->col); rowIndex = std::max(searchNode->nodeData->matrixIndex->rowIndex - 1, 0); colIndex = std::max(searchNode->nodeData->matrixIndex->colIndex - 1, 0); for (i = rowIndex; i < row; i ++) { for (j = colIndex; j < col; j ++) { MapNode* checkNode = map->getMapNode(i, j); /**是否和检测的节点相等**/ bool b1 = MapUtils::checkNode(searchNode, checkNode); /**是否容许通过**/ bool b2 = MapUtils::checkAllow(checkNode); /**斜角是否容许通过**/ bool b3 = MapUtils::checkAllow(map->getMapNode(searchNode->nodeData->matrixIndex->rowIndex, checkNode->nodeData->matrixIndex->colIndex)); /**斜角是否容许通过**/ bool b4 = MapUtils::checkAllow(map->getMapNode(searchNode->nodeData->matrixIndex->colIndex, checkNode->nodeData->matrixIndex->rowIndex)); if (b1 == true || b2 == false || b3 == false || b4 == false) { continue; } if (searchNode->nodeData->matrixIndex->rowIndex != checkNode->nodeData->matrixIndex->rowIndex && searchNode->nodeData->matrixIndex->colIndex != checkNode->nodeData->matrixIndex->colIndex) { g = searchNode->g + ANGLE; } else { g = searchNode->g + NORMAL; } h = MapUtils::calculateH(checkNode, endNode); f = g + h; if (checkNode->isOpen == true || checkNode->isClose == true) { if (checkNode->f > f) { checkNode->f = f; checkNode->h = h; checkNode->g = g; checkNode->father = searchNode; } } else { checkNode->f = f; checkNode->h = h; checkNode->g = g; checkNode->father = searchNode; checkNode->isOpen = true; openList->addObject(checkNode); } } } searchNode->isClose = true; closeList->addObject(searchNode); if (openList->count() <= 0) { return NULL; } searchNode = MapUtils::getMinF(openList);/**获取f值最小的节点,并且从openList中删除**/ searchNode->isOpen = false; } clearCloseList(closeList); clearOpenList(openList); delete openList; delete closeList; return searchNode; }
int CCLuaEngine::executeNodeTouchesEvent(CCNode* pNode, int eventType, CCSet *pTouches, int phase) { m_stack->clean(); CCLuaValueDict event; switch (eventType) { case CCTOUCHBEGAN: event["name"] = CCLuaValue::stringValue("began"); break; case CCTOUCHMOVED: event["name"] = CCLuaValue::stringValue("moved"); break; case CCTOUCHENDED: event["name"] = CCLuaValue::stringValue("ended"); break; case CCTOUCHCANCELLED: event["name"] = CCLuaValue::stringValue("cancelled"); break; case CCTOUCHADDED: event["name"] = CCLuaValue::stringValue("added"); break; case CCTOUCHREMOVED: event["name"] = CCLuaValue::stringValue("removed"); break; default: return 0; } event["mode"] = CCLuaValue::intValue(kCCTouchesAllAtOnce); switch (phase) { case NODE_TOUCH_CAPTURING_PHASE: event["phase"] = CCLuaValue::stringValue("capturing"); break; case NODE_TOUCH_TARGETING_PHASE: event["phase"] = CCLuaValue::stringValue("targeting"); break; default: event["phase"] = CCLuaValue::stringValue("unknown"); } CCLuaValueDict points; CCDirector* pDirector = CCDirector::sharedDirector(); char touchId[16]; for (CCSetIterator touchIt = pTouches->begin(); touchIt != pTouches->end(); ++touchIt) { CCLuaValueDict point; CCTouch* pTouch = (CCTouch*)*touchIt; sprintf(touchId, "%d", pTouch->getID()); point["id"] = CCLuaValue::stringValue(touchId); const CCPoint pt = pDirector->convertToGL(pTouch->getLocationInView()); point["x"] = CCLuaValue::floatValue(pt.x); point["y"] = CCLuaValue::floatValue(pt.y); const CCPoint prev = pDirector->convertToGL(pTouch->getPreviousLocationInView()); point["prevX"] = CCLuaValue::floatValue(prev.x); point["prevY"] = CCLuaValue::floatValue(prev.y); points[touchId] = CCLuaValue::dictValue(point); } event["points"] = CCLuaValue::dictValue(points); m_stack->pushCCLuaValueDict(event); int eventInt = (phase == NODE_TOUCH_CAPTURING_PHASE) ? NODE_TOUCH_CAPTURE_EVENT : NODE_TOUCH_EVENT; CCArray *listeners = pNode->getAllScriptEventListeners(); CCScriptHandlePair *p; for (int i = listeners->count() - 1; i >= 0; --i) { p = dynamic_cast<CCScriptHandlePair*>(listeners->objectAtIndex(i)); if (p->event != eventInt || p->removed) continue; m_stack->copyValue(1); m_stack->executeFunctionByHandler(p->listener, 1); m_stack->settop(1); } m_stack->clean(); return 1; }
void FirstLevel::update(float dt) { /*parallax */ CCPoint backgroundScrollVert = ccp(-1000,0) ; _background->setPosition(ccpAdd(_background->getPosition(),ccpMult(backgroundScrollVert,dt))); CCArray *spaceDusts = CCArray::createWithCapacity(2); spaceDusts->addObject(_spacedust1) ; spaceDusts->addObject(_spacedust2) ; for (int i = 0; i < spaceDusts->count(); i++ ) { CCSprite * spaceDust = (CCSprite *)(spaceDusts->objectAtIndex(i)) ; float xPosition = _background->convertToWorldSpace(spaceDust->getPosition()).x; float size = spaceDust->getContentSize().width ; if (xPosition < -size) _background->incrementOffset(ccp(spaceDust->getContentSize().width*2,0),spaceDust); } /*end parallax */ /*accelerometer*/ float maxY = winSize.height - _ship->getContentSize().height/2; float minY = _ship->getContentSize().height/2; float diff = _shipPositionY * dt; float newY = _ship->getPosition().y + diff; newY = MIN(MAX(newY, minY), maxY); _ship->setPosition(ccp(_ship->getPosition().x, newY)); /*end accelerometer*/ /*first we move sprites and then bodies*/ /*sprites animation*/ float curTime = getTimeTick(); if (curTime > _nextAsteroidSpawn){ // if time to show new asteroid? float randY = randomBetween(0, winSize.height); // new asteroid position float randms = randomBetween(0.2, 1.0)*1000; // how often show new asteroid _nextAsteroidSpawn = randms + curTime; // when show next asteroid float duration = randomBetween(1.0, 7.0); // android's "speed" Asteroid* asteroid = _asteroids->at(_nextAsteroid++); if(_nextAsteroid >= _asteroids->size()) _nextAsteroid = 0; /*take asteroid from cage and set next params; *when asteroid end moving - hide */ asteroid->stopAllActions(); asteroid->setPosition(ccp(winSize.width + asteroid->getContentSize().width/2, randY)); asteroid->setLives(3); asteroid->setVisible(true); asteroid->runAction(CCSequence::create(CCMoveBy::create(duration,ccp( -winSize.width - asteroid->getContentSize().width, 0)), CCCallFuncN::create(this, callfuncN_selector(FirstLevel::setInvisible)),NULL)); } /*end sprites animation*/ /*bodies animation*/ _world->Step(dt, 10, 10); for(b2Body *b = _world->GetBodyList(); b; b = b->GetNext()){ if (b->GetUserData() != NULL){ CCSprite* sprite = (CCSprite*) b->GetUserData(); if (sprite->isVisible()) { b2Vec2 position = b2Vec2(sprite->getPosition().x/PTM_RATIO, sprite->getPosition().y/PTM_RATIO); float angle = -1 * CC_DEGREES_TO_RADIANS(sprite->getRotation()); b->SetTransform(position, angle); } } } /*end bodies animation*/ /*body's collisions*/ std::deque<CurrentContact>::iterator i; for(i = _collisionListener->contacts.begin(); i != _collisionListener->contacts.end(); ++i){ CurrentContact contact = *i; b2Body *a = contact.a->GetBody(); b2Body *b = contact.b->GetBody(); if (a->GetUserData() != NULL && b->GetUserData() != NULL){ CCSprite *sA = (CCSprite*)a->GetUserData(); CCSprite *sB = (CCSprite*)b->GetUserData(); Asteroid *ast; CCSprite *bullet; if (sA->isVisible() && sB->isVisible()) { /*asteroid and bullet (laser)*/ //if (sA->getTag() != 0 || sB->getTag() != 0) if ((sA->getTag() == 1 && sB->getTag() == 2) || (sA->getTag() == 2 && sB->getTag() == 1)) { b2Body *temp; // bullet body if (sA->getTag() == 1) { ast = (Asteroid*) a->GetUserData(); bullet = (CCSprite*) b->GetUserData(); temp = b; } else { ast = (Asteroid*) b->GetUserData(); bullet = (CCSprite*) a->GetUserData(); temp = a; } if (ast->getLives() > 1){ // hide only bullet ast->subLife(); temp->SetTransform(b2Vec2(-100.0, -100.0), 0.0f); // bullet body } else { // hide asteroid and bullet a->SetTransform(b2Vec2(-100.0, -100.0), 0.0f); b->SetTransform(b2Vec2(-100.0, -100.0), 0.0f); ast->stopAllActions(); ast->setVisible(false); _ship->addScore(score); updateScore(_ship); } bullet->stopAllActions(); bullet->setVisible(false); continue; } /*asteroid and ship*/ if ((sA->getTag() == 0 && sB->getTag() == 1) || (sA->getTag() == 1 && sB->getTag() == 0)) { if (_ship->getLives() > 0){ _ship->subLife(); updateLives(_ship); _ship->runAction(CCBlink::create(1.0, 3)); if (sA->getTag() == 1){ sA->setVisible(false); sA->stopAllActions(); a->SetTransform(b2Vec2(-100.0, -100.0), 0.0f); } else { sB->setVisible(false); sB->stopAllActions(); b->SetTransform(b2Vec2(-100.0, -100.0), 0.0f); } } else { CCLog("GAME OVER"); // TODO: show dialog } continue; } } } } /*end body's collisions*/ }
int CCLuaEngine::executeNodeTouchEvent(CCNode* pNode, int eventType, CCTouch *pTouch, int phase) { m_stack->clean(); CCLuaValueDict event; switch (eventType) { case CCTOUCHBEGAN: event["name"] = CCLuaValue::stringValue("began"); break; case CCTOUCHMOVED: event["name"] = CCLuaValue::stringValue("moved"); break; case CCTOUCHENDED: event["name"] = CCLuaValue::stringValue("ended"); break; case CCTOUCHCANCELLED: event["name"] = CCLuaValue::stringValue("cancelled"); break; default: CCAssert(false, "INVALID touch event"); return 0; } event["mode"] = CCLuaValue::intValue(kCCTouchesOneByOne); switch (phase) { case NODE_TOUCH_CAPTURING_PHASE: event["phase"] = CCLuaValue::stringValue("capturing"); break; case NODE_TOUCH_TARGETING_PHASE: event["phase"] = CCLuaValue::stringValue("targeting"); break; default: event["phase"] = CCLuaValue::stringValue("unknown"); } const CCPoint pt = CCDirector::sharedDirector()->convertToGL(pTouch->getLocationInView()); event["x"] = CCLuaValue::floatValue(pt.x); event["y"] = CCLuaValue::floatValue(pt.y); const CCPoint prev = CCDirector::sharedDirector()->convertToGL(pTouch->getPreviousLocationInView()); event["prevX"] = CCLuaValue::floatValue(prev.x); event["prevY"] = CCLuaValue::floatValue(prev.y); m_stack->pushCCLuaValueDict(event); int eventInt = (phase == NODE_TOUCH_CAPTURING_PHASE) ? NODE_TOUCH_CAPTURE_EVENT : NODE_TOUCH_EVENT; CCArray *listeners = pNode->getAllScriptEventListeners(); CCScriptHandlePair *p; int ret = 1; for (int i = listeners->count() - 1; i >= 0; --i) { p = dynamic_cast<CCScriptHandlePair*>(listeners->objectAtIndex(i)); if (p->event != eventInt || p->removed) continue; if (eventType == CCTOUCHBEGAN) { // enable listener when touch began p->enabled = true; } if (p->enabled) { m_stack->copyValue(1); int listenerRet = m_stack->executeFunctionByHandler(p->listener, 1); if (listenerRet == 0) { if (phase == NODE_TOUCH_CAPTURING_PHASE && (eventType == CCTOUCHBEGAN || eventType == CCTOUCHMOVED)) { ret = 0; } else if (phase == NODE_TOUCH_TARGETING_PHASE && eventType == CCTOUCHBEGAN) { // if listener return false when touch began, disable this listener p->enabled = false; ret = 0; } } m_stack->settop(1); } } //CCLOG("executeNodeTouchEvent %p, ret = %d, event = %d, phase = %d", pNode, ret, eventType, phase); m_stack->clean(); return ret; }
void SGLootWiKiLayer::showCream(CCObject * sender) { SGSocketRequest *req = (SGSocketRequest *)sender; main::BossPlotListResponse *response = (main::BossPlotListResponse *)req->m_msg; CCArray * array = SGPlayerInfo::sharePlayerInfo()->getStoryData(); if (response) { int index = array->count() - (m_plotId - 20000); if (index >= 0 && index < array->count()) { SGStoryBean *story = (SGStoryBean *)array->objectAtIndex( index ); //精英关卡的排序是反向的!最初的关卡索引反而大! int size = response->bossplotmodel_size(); if (size > 0) { for (int ii = 0; ii < size; ii++) { main::BossPlotModel model = response->bossplotmodel(ii); CCLOG("scene ID=================%d", model.plotid()); SGStorySceneBean *scene = story->getSceneBeanById(model.plotid()); if (scene == NULL) { continue; } else { scene->setVisible(true); //scene->setRank(model.ra); scene->setPower(model.power()); scene->setGold(model.gold()); scene->setExp(model.exp()); scene->setZhandou(model.zhandou()); scene->setRank(model.rank()); scene->setCreamCanJoin(model.canjoin()); //数据存储在playerinfo中 SGPlayerInfo::sharePlayerInfo()->setCreamData(model.plotid(), model.canjoincount(), model.canjoin()); scene->setCreamDayTimes(model.canjoincount()); scene->setCreamBuyTimes(model.canbuycount()); scene->setBuyPrice(model.price()); scene->setBuyCompTimes(model.buycount());// 已经购买次数 scene->setDropInfo(model.exp(), model.gold()); //精英闯关 剩余次数存储在playerinfo中 //SGPlayerInfo::sharePlayerInfo()->setLeftCreamTimes(model.canjoincount()); int itemNum = model.itemids_size(); scene->itemIds.clear(); for (int jj =0;jj<itemNum; jj++) { scene->itemIds.push_back(model.itemids(jj)); } } SGPlayerInfo::sharePlayerInfo()->setMaxBossPlotId(model.plotid()); } } //假如可能出现问题,也能跳关,只是关卡会显示不正确。 SGMainManager::shareMain()->showStorySectionLayer(story); } //不判断该关卡是否能打,交给精英节列表的逻辑。 // if(!SGPlayerInfo::sharePlayerInfo()->getCreamIsCanJoin(SGMainManager::static_plotId)) // { // int leftJoinCount = SGStaticDataManager::shareStatic()->getCreamByPlotId(SGMainManager::static_plotId)->getCreamDayTimes() - SGPlayerInfo::sharePlayerInfo()->getCreamJoinedCount(SGMainManager::static_plotId) ; // SGMainManager::shareMain()->showMessage(str_lootWiKi_10); // SGMainManager::sourceToStory = false; // } // else { SGMainManager::shareMain()->m_trackIsPve = false; m_lootWikiMainLayer->boxClose(); } } SGMainManager::sourceToStory = false; }
void setRequestDialogParamsJni(jobject obj, CCDictionary *params){ JniMethodInfo t; if(params == NULL){ return; } if(JniHelper::getMethodInfo(t, "java/util/TreeMap", "<init>", "()V")){ jobject map = t.env->NewObject(t.classID, t.methodID); if(map == NULL){ CCLog("Cannot create new TreeMap objeect in %S", __func__); return; } JniMethodInfo m; if(GreeJniHelper::getInstanceMethodInfo(m, map, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;")){ CCDictElement* pElement = NULL; CCDICT_FOREACH(params, pElement){ const std::string str = pElement->getStrKey(); const char *pStr = str.c_str(); jstring jStr; if(!pStr){ jStr = t.env->NewStringUTF(""); }else{ jStr = t.env->NewStringUTF(pStr); } if(!strncmp(GD_REQUEST_DIALOG_PARAM_KEY_TITLE, pStr, sizeof(GD_REQUEST_DIALOG_PARAM_KEY_TITLE)) || !strncmp(GD_REQUEST_DIALOG_PARAM_KEY_BODY, pStr, sizeof(GD_REQUEST_DIALOG_PARAM_KEY_BODY)) || !strncmp(GD_REQUEST_DIALOG_PARAM_KEY_LISTTYPE, pStr, sizeof(GD_REQUEST_DIALOG_PARAM_KEY_LISTTYPE)) || !strncmp(GD_REQUEST_DIALOG_PARAM_KEY_EXPIRETIME, pStr, sizeof(GD_REQUEST_DIALOG_PARAM_KEY_EXPIRETIME))){ // title, body, list_type, expire_time CCString *val = ((CCString *)(pElement->getObject())); if(val == NULL){ return; } const char *pVal = val->getCString(); jstring jVal; if(!pVal){ jVal = t.env->NewStringUTF(""); }else{ jVal = t.env->NewStringUTF(pVal); } m.env->CallObjectMethod(map, m.methodID, jStr, jVal); m.env->DeleteLocalRef(jVal); }else if(!strncmp(GD_REQUEST_DIALOG_PARAM_KEY_TOUSERID, pStr, sizeof(GD_REQUEST_DIALOG_PARAM_KEY_TOUSERID))){ //touserid CCArray *array = ((CCArray *)(pElement->getObject())); if(array == NULL){ return; } jclass jcl = JniHelper::getClassID("java/lang/String"); if(jcl == NULL){ return; } jobjectArray jarry = t.env->NewObjectArray(array->count(), jcl, NULL); CCObject *it; int i = 0; CCARRAY_FOREACH(array, it){ CCString *val = dynamic_cast<CCString *>(it); const char *pVal = val->getCString(); jstring jVal; if(!pVal){ jVal = t.env->NewStringUTF(""); }else{ jVal = t.env->NewStringUTF(pVal); } t.env->SetObjectArrayElement(jarry, i, jVal); t.env->DeleteLocalRef(jVal); i++; } m.env->CallObjectMethod(map, m.methodID, jStr, jarry); t.env->DeleteLocalRef(jarry); }else if(!strncmp(GD_REQUEST_DIALOG_PARAM_KEY_ATTRS, pStr, sizeof(GD_REQUEST_DIALOG_PARAM_KEY_ATTRS))){
/// Callback function used by libcurl for collect header data static size_t writeHeaderData(void* ptr, size_t size, size_t nmemb, void* userdata) { CURLHandler* handler = (CURLHandler*)userdata; size_t sizes = size * nmemb; // lock pthread_mutex_lock(&handler->m_mutex); // parse pair string header((const char*)ptr, sizes); CCArray* pair = new CCArray(); if(!header.empty()) { // remove head and tailing brace, bracket, parentheses size_t start = 0; size_t end = header.length() - 1; char c = header[start]; while(c == '{' || c == '[' || c == '(') { start++; c = header[start]; } c = header[end]; while(c == '}' || c == ']' || c == ')') { end--; c = header[end]; } // iterate string size_t compStart = start; for(size_t i = start; i <= end; i++) { c = header[i]; if(c == ':') { CCString* s = new CCString(header.substr(compStart, i - compStart)); pair->addObject(s); s->release(); compStart = i + 1; } else if(c == ' ' || c == '\t' || c == '\r' || c == '\n') { if(compStart == i) { compStart++; } } } // last comp // or, if last char is separator, append an empty string if(compStart <= end) { CCString* s = new CCString(header.substr(compStart, end - compStart + 1)); pair->addObject(s); s->release(); } else if(header[end] == ':') { CCString* s = new CCString(""); pair->addObject(s); s->release(); } } // if pair count is two, means ok if(pair->count() == 2) { handler->m_ctx->response->addHeader(((CCString*)pair->objectAtIndex(0))->getCString(), ((CCString*)pair->objectAtIndex(1))->getCString()); } // release array pair->release(); // unlock pthread_mutex_unlock(&handler->m_mutex); // return a value which is different with sizes will abort it if(handler->m_ctx->request->isCancel()) return sizes + 1; else return sizes; }
void BuildScroll::createMenuItems() { // set common variables CCSize screenSize = CCDirector::sharedDirector()->getWinSize(); // create the build group background string buildBackground = "scrollermiddle_b.png"; buildMenu = CCSprite::createWithSpriteFrameName(buildBackground.c_str()); CCSize spriteSize = buildMenu->getContentSize(); buildMenu->setAnchorPoint(ccp(0, 0)); buildMenu->setScale(screenSize.width / spriteSize.width * 0.98f); buildMenu->setPosition(ccp(screenSize.width * (1.01f - leftPos), 25)); this->addChild(buildMenu, 1); scrollerBar = CCSprite::createWithSpriteFrameName("scroller_side.png"); scrollerBar->setAnchorPoint(ccp(0, 0)); scrollerBar->setScale(screenSize.width / spriteSize.width * 0.98f); scrollerBar->setPosition(ccp(screenSize.width * (1.0f - leftPos), 0)); this->addChild(scrollerBar, 2); // scroll section for other villagers scrollArea = new ScrollArea(); scrollArea->createScrollArea(CCSizeMake(buildMenu->boundingBox().size.width * 0.96f, buildMenu->boundingBox().size.height * 0.92f), CCSizeMake(BuildingHandler::getThis()->allBuildings->count() , buildMenu->boundingBox().size.height * 0.92f)); scrollArea->enableScrollHorizontal(0, "bar.png", "bar.png"); scrollArea->setAnchorPoint(ccp(0, 0)); // create all building references for all building categories. CCArray* allBuildings = BuildingHandler::getThis()->allBuildings; // list down all the buildings numberOfBuildingCards = 0; BuildingCard* bc = BuildingCard::create(NULL, scrollArea, numberOfBuildingCards, 1); numberOfBuildingCards++; buildingCards->addObject(bc); bc = BuildingCard::create(NULL, scrollArea, numberOfBuildingCards, 2); numberOfBuildingCards++; buildingCards->addObject(bc); bc = BuildingCard::create(NULL, scrollArea, numberOfBuildingCards, 3); numberOfBuildingCards++; buildingCards->addObject(bc); for(int i = 0; i < allBuildings->count(); i++) { Building* tempBuilding = (Building*) allBuildings->objectAtIndex(i); if(tempBuilding->buildingType == HOUSING) { if (!nameExists(tempBuilding->buildingName)) { bc = BuildingCard::create(tempBuilding, scrollArea, numberOfBuildingCards, 0); numberOfBuildingCards++; buildingCards->addObject(bc); } } } for(int i = 0; i < allBuildings->count(); i++) { Building* tempBuilding = (Building*) allBuildings->objectAtIndex(i); if(tempBuilding->buildingType == AMENITY) { // if (!nameExists(tempBuilding->buildingName)) // { bc = BuildingCard::create(tempBuilding, scrollArea, numberOfBuildingCards, 0); numberOfBuildingCards++; buildingCards->addObject(bc); // } } } for(int i = 0; i < allBuildings->count(); i++) { Building* tempBuilding = (Building*) allBuildings->objectAtIndex(i); if(tempBuilding->buildingType == GRANARY) { bc = BuildingCard::create(tempBuilding, scrollArea, numberOfBuildingCards, 0); numberOfBuildingCards++; buildingCards->addObject(bc); } } for(int i = 0; i < allBuildings->count(); i++) { Building* tempBuilding = (Building*) allBuildings->objectAtIndex(i); if(tempBuilding->buildingType == MARKET) { bc = BuildingCard::create(tempBuilding, scrollArea, numberOfBuildingCards, 0); numberOfBuildingCards++; buildingCards->addObject(bc); } } for(int i = 0; i < allBuildings->count(); i++) { Building* tempBuilding = (Building*) allBuildings->objectAtIndex(i); if(tempBuilding->buildingType == MILITARY) { bc = BuildingCard::create(tempBuilding, scrollArea, numberOfBuildingCards, 0); numberOfBuildingCards++; buildingCards->addObject(bc); } } if(UserProfile::getThis()->gameLevel != 0) { for (int i = 0; i < allBuildings->count(); i++) { Building* tempBuilding = (Building*) allBuildings->objectAtIndex(i); if(tempBuilding->buildingType == SOCIAL) { bc = BuildingCard::create(tempBuilding, scrollArea, numberOfBuildingCards, 0); numberOfBuildingCards++; buildingCards->addObject(bc); } } } scrollArea->setScrollContentSize(CCSizeMake(10.0f + screenSize.width * 0.19f * numberOfBuildingCards, buildMenu->boundingBox().size.height * 0.92f)); scrollArea->setPosition(ccp(screenSize.width * 0.06f + screenSize.width * (maxPos - leftPos), buildMenu->boundingBox().size.height * 0.14f)); scrollArea->updateScrollBars(); this->addChild(scrollArea, 1); scroll_in = true; this->schedule(schedule_selector( BuildScroll::scrollIn ), 1/120.0f); }
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; }
void MailInfo::parse(cocos2d::CCDictionary *dic){ isThanks=false; saveDict=NULL; isShare=false; contents = ""; detecterName = ""; ckfContents = ""; pic = ""; allianceLang = ""; msReport = 0; picVer = 0; ckf = 0; serverType = 0; mbLevel = 0; isWorldBossKillRewardMail = false; if(dic->objectForKey("pic")){ pic = dic->valueForKey("pic")->getCString(); } if (dic->objectForKey("picVer")) { picVer = dic->valueForKey("picVer")->intValue(); } type = dic->valueForKey("type")->intValue(); //define tabType if(type==MAIL_BATTLE_REPORT||type==MAIL_DETECT||type==MAIL_DETECT_REPORT||type==MAIL_ENCAMP||type==MAIL_WORLD_BOSS){ tabType = 4; }else if(type==ALL_SERVICE){ tabType = 3; }else if(type== MAIL_FRESHER||type==MAIL_SYSNOTICE||type==MAIL_SYSUPDATE){ tabType = 2; }else if(type <=MAIL_USER||type==MAIL_Alliance_ALL||type==CHAT_ROOM){ tabType = 0; }else if(type == MAIL_MOD_SEND || type == MAIL_MOD_PERSONAL){ if(GlobalData::shared()->playerInfo.gmFlag == 2 || GlobalData::shared()->playerInfo.gmFlag == 5){ tabType = 5; }else{ tabType = 0; } }else{ tabType = 1; } if(dic->objectForKey("uid")) uid = dic->valueForKey("uid")->getCString(); else uid=""; createTime = dic->valueForKey("createTime")->doubleValue() / 1000; CCLOGFUNCF("createTime: %ld",createTime); if(dic->objectForKey("mbLevel")) { mbLevel=dic->valueForKey("mbLevel")->intValue(); } rewardId = dic->valueForKey("rewardId")->getCString(); int status1 = dic->valueForKey("status")->intValue(); if(status1>0){ if(status1==2){ isThanks=true; } status = READ; }else{ status = UNREAD; } fromName = dic->valueForKey("oldName")->getCString(); nowName = dic->valueForKey("fromName")->getCString(); modLanguage = dic->valueForKey("modLanguage")->getCString(); if(fromName.empty() && !nowName.empty()){ fromName = nowName; } if(dic->objectForKey("fromUid")){ fromUid = dic->valueForKey("fromUid")->getCString(); } else if(dic->objectForKey("fromUser")) { fromUid = dic->valueForKey("fromUser")->getCString(); } else{ fromUid = ""; } if(dic->objectForKey("share")){ isShare = dic->valueForKey("share")->boolValue(); } if (dic->objectForKey("donate")) { goToDonate = dic->valueForKey("donate")->intValue(); } reply = dic->valueForKey("reply")->intValue(); alliance = dic->valueForKey("alliance")->getCString(); version = dic->valueForKey("version")->getCString(); rewardStatus = dic->valueForKey("rewardStatus")->intValue(); battleType = dic->valueForKey("battleType")->intValue(); title = dic->valueForKey("title")->getCString(); itemIdFlag = dic->valueForKey("itemIdFlag")->intValue(); unreadDialogNum = dic->valueForKey("unread")->intValue(); dialogNum = dic->valueForKey("totalNum")->intValue(); userKill = dic->valueForKey("userKill")->intValue(); allKill = dic->valueForKey("allKill")->intValue(); msReport = dic->valueForKey("msReport")->intValue(); failTimes = dic->valueForKey("failTimes")->intValue(); winPercent = dic->valueForKey("winPercent")->intValue(); killRound = dic->valueForKey("killRound")->intValue(); userScore = dic->valueForKey("userScore")->intValue(); monsterLevel = dic->valueForKey("monsterLevel")->intValue(); like = dic->valueForKey("like")->intValue(); if(dic->objectForKey("serverType")){ serverType = dic->valueForKey("serverType")->intValue(); } if(dic->objectForKey("contents")){ showContent = dic->valueForKey("contents")->getCString(); } if(type <= MAIL_USER || type == MAIL_MOD_SEND || type == MAIL_MOD_PERSONAL || type == CHAT_ROOM){ }else if(type == MAIL_RESOURCE_HELP){ fromName = _lang("114121"); }else if(type == MAIL_RESOURCE){ fromName = _lang("105516"); if(title == ""){ title = "1,1"; } vector<std::string> vector; CCCommonUtils::splitString(title, ",", vector); int level = 0; int type = 0; if(vector.size()>=2){ level = atoi(vector[0].c_str()); type = atoi(vector[1].c_str()); } title = string("Lv.") + CC_ITOA(level) + " " + CCCommonUtils::getResourceProductByType(type); showContent = _lang_1("105517", title.c_str()); }else if(type == MAIL_DETECT){ if(itemIdFlag == 1){ std::string contentId = dic->valueForKey("contents")->getCString(); if(!contentId.empty() && contentId.length()>6){ contentId = contentId.substr(6); if(contentId=="105554"){ fromName = _lang("105523"); title = showContent; } } }else{ std::string contentId = dic->valueForKey("contents")->getCString(); // if(contentId=="105554"){ // fromName = _lang("105523"); // title = _lang("105554"); // }else{ // fromName = _lang("105522"); // } fromName = _lang("105522"); if(title.compare("1") == 0){ title = _lang("105523"); }else{ title = _lang("105567"); } } } else if(type == MAIL_DETECT_REPORT){ std::string contentId = dic->valueForKey("contents")->getCString(); if(contentId.compare("114005") == 0){ pointType = MAIL_DETECT_REPORT_PROTECT; fromName = _lang("105522"); title = _lang("114102"); showContent = _lang("114005"); }else{ fromName = _lang("105522"); //title = _lang("105523"); showContent = ""; switch (pointType) { case Throne:{ //王座 showContent = _lang("105708"); break; } case Trebuchet:{//投石机 showContent = _lang("105709"); break; } default:{ showContent = _lang("105527"); break; } } } }else if(type == MAIL_ENCAMP){ fromName = _lang("105536"); switch (pointType) { case Throne:{ title = _lang("105710"); break; } case Trebuchet:{ title = _lang("105711"); break; } default:{ if(this->isTreasureMap){ fromName = _lang("111504"); title = _lang("111504"); }else{ title = _lang("105537"); } break; } } }else if(type == MAIL_WOUNDED){ fromName = _lang("105305"); title = _lang("105550"); }else if(type == MAIL_BATTLE_REPORT){ if(dic->objectForKey("contents")){ auto tempDic = _dict(dic->objectForKey("contents")); if(tempDic!=NULL){ int pos = tempDic->valueForKey("warPoint")->intValue(); CCPoint pt = WorldController::getPointByIndex(pos); if (serverType>=SERVER_BATTLE_FIELD) { pt = WorldController::getPointByMapTypeAndIndex(pos,(MapType)serverType); } //fromName = _lang_2("105518",CC_ITOA(pt.x),CC_ITOA(pt.y)); std::string npcId = ""; if( tempDic->objectForKey("npcId")) npcId= tempDic->valueForKey("npcId")->getCString(); std::string defName =""; if(npcId!=""){ defName = CCCommonUtils::getNameById(tempDic->valueForKey("npcId")->getCString()); }else{ if (tempDic->objectForKey("defName")) { defName = tempDic->valueForKey("defName")->getCString(); } } std::string attName = tempDic->valueForKey("atkName")->getCString(); if(GlobalData::shared()->playerInfo.name==attName){ title = _lang_2("105547",_lang("102187").c_str(),defName.c_str()); }else{ title = _lang_2("105547",attName.c_str(),_lang("108678").c_str()); } int win = tempDic->valueForKey("win")->intValue(); std::string result = ""; if(win==0){ result = _lang("105117"); }else if(win==1){ result = _lang("105118"); }else{ result = _lang("105549"); } showContent = _lang_1("105548", result.c_str()); fromName = result; } } }else if(type == MAIL_DIGONG || type == WORLD_NEW_EXPLORE){ title = _lang("108675"); }else if(type == MAIL_ATTACKMONSTER){ fromName = _lang("103715"); }else if(type==MAIL_Alliance_ALL || type == MAIL_GIFT){ }else if(type == MAIL_DONATE){ fromName = _lang("105305"); std::string contentId = dic->valueForKey("contents")->getCString(); vector<string> mVStr; CCCommonUtils::splitString(contentId, "|", mVStr); if(mVStr.size()>4){ std::string userName = mVStr.at(1); if (!mVStr.at(2).empty()) { userName = "******" + mVStr.at(2) +")" + userName; } title = _lang_1("101007",userName.c_str()); contents = _lang_3(mVStr.at(0), userName.c_str(), mVStr.at(3).c_str(), mVStr.at(4).c_str()); showContent = contents; } itemIdFlag = 0; }else{ fromName = _lang("105305"); } prepareToDelete = false; save = dic->valueForKey("save")->intValue(); isRead = false; if(itemIdFlag == 1){ //杀死世界boss领奖邮件 if (title=="137460") { type=MAIL_WORLD_BOSS; isWorldBossKillRewardMail = true; } title = _lang(title); string fromdl = dic->valueForKey("fromName")->getCString(); if(fromdl != ""){ string fromNL = _lang(fromdl); if(fromNL!=""){ fromName = fromNL; } } if(showContent != ""){ showContent = _lang(showContent); } } if(type == MAIL_FRESHER){ fromName = _lang("3000001"); } // std::string contentId = dic->valueForKey("contents")->getCString(); // if(contentId=="114005"){ // fromName = _lang("114102"); // title = _lang("114005"); // }else if(contentId!=""&&contentId.length()>6){ // contentId = contentId.substr(6); // if(contentId=="105554"){ // fromName = _lang("105523"); // title = showContent; // } // } if(tabType==0 || type == MAIL_MOD_PERSONAL || type == MAIL_MOD_SEND || type==CHAT_ROOM){ if(dialogs==NULL) { dialogs=CCArray::create(); dialogs->retain(); } contents = showContent; title = contents; if(dic->objectForKey("chats")){ CCArray *arr = dynamic_cast<CCArray*>(dic->objectForKey("chats")); CCObject* obj; int count = arr->count(); int i = 0; CCARRAY_FOREACH(arr, obj){ CCDictionary* dictDialog = dynamic_cast<CCDictionary*>(obj); MailDialogInfo* dialogInfo = MailDialogInfo::create(); dialogInfo->parse(dictDialog); this->dialogs->addObject(dialogInfo); if(i==count-1){ title = dialogInfo->contents; } i++; } }
void appendObject(CCObject* obj, xml_node& node) { if(isKindOfClass(obj, CCDictionary)) { //CCLOG("Dictionary recognized"); CCDictionary* dict = (CCDictionary*)obj; xml_node children = node.append_child("dict"); CCArray* keys = dict->allKeys(); if(keys != NULL) { for(int i = 0; i < keys->count(); i++) { CCString* key = (CCString*)keys->objectAtIndex(i); children.append_child("key").append_child(node_pcdata).set_value(key->getCString()); appendObject(dict->objectForKey(key->getCString()), children); } } } else if(isKindOfClass(obj, CCArray)) { //CCLOG("Array recognized"); CCArray* array = (CCArray*)obj; xml_node children = node.append_child("array"); for(int i = 0; i < array->count(); i++) { CCObject* child = (CCObject*)array->objectAtIndex(i); appendObject(child, children); } } else if (isKindOfClass(obj, CCString)) { //CCLOG("String recognized"); node.append_child("string").append_child(node_pcdata).set_value(((CCString*)obj)->getCString()); } else if (isKindOfClass(obj, CCInteger)) { //CCLOG("Integer recognized"); int value = TOINT(obj); CCString* stringVal = ScreateF("%d", value); node.append_child("integer").append_child(node_pcdata).set_value(stringVal->getCString()); } else if (isKindOfClass(obj, CCFloat)) { //CCLOG("Float recognized"); float value = TOFLOAT(obj); CCString* stringVal = ScreateF("%g", value); node.append_child("real").append_child(node_pcdata).set_value(stringVal->getCString()); } else if (isKindOfClass(obj, CCBool)) { //CCLOG("Bool recognized"); bool value = TOBOOL(obj); node.append_child(value ? "true" : "false"); } #if VERBOSE_SAVE_PLIST else { CCLOG("Warning: unrecognized type %s when saving plist, check if the object is in plist format", typeid(*obj).name()); } #endif }
void GB2ShapeCache::addShapesWithFile(const std::string &plist) { CCDictionary *dict = CCDictionary::dictionaryWithContentsOfFileThreadSafe(plist.c_str()); CCAssert(dict != NULL, "Shape-file not found"); // not triggered - cocos2dx delivers empty dict if non was found CCAssert(dict->count() != 0, "plist file empty or not existing"); CCDictionary *metadataDict = (CCDictionary *)dict->objectForKey("metadata"); int format = static_cast<CCString *>(metadataDict->objectForKey("format"))->intValue(); ptmRatio = static_cast<CCString *>(metadataDict->objectForKey("ptm_ratio"))->floatValue(); CCAssert(format == 1, "Format not supported"); CCDictionary *bodyDict = (CCDictionary *)dict->objectForKey("bodies"); b2Vec2 vertices[b2_maxPolygonVertices]; CCDictElement* pElement = NULL; CCDICT_FOREACH(bodyDict, pElement) { BodyDef *bodyDef = new BodyDef(); CCString *bodyName = ccs(pElement->getStrKey()); CCDictionary *bodyData = (CCDictionary *)pElement->getObject(); bodyDef->anchorPoint = CCPointFromString(static_cast<CCString *>(bodyData->objectForKey("anchorpoint"))->getCString()); CCArray *fixtureList = (CCArray *)bodyData->objectForKey("fixtures"); FixtureDef **nextFixtureDef = &(bodyDef->fixtures); CCObject *fixture = NULL; CCARRAY_FOREACH(fixtureList, fixture) { b2FixtureDef basicData; CCDictionary *fixtureData = (CCDictionary *)fixture; int callbackData = 0; basicData.filter.categoryBits = static_cast<CCString *>(fixtureData->objectForKey("filter_categoryBits"))->intValue(); basicData.filter.maskBits = static_cast<CCString *>(fixtureData->objectForKey("filter_maskBits"))->intValue(); basicData.filter.groupIndex = static_cast<CCString *>(fixtureData->objectForKey("filter_groupIndex"))->intValue(); basicData.friction = static_cast<CCString *>(fixtureData->objectForKey("friction"))->floatValue(); basicData.density = static_cast<CCString *>(fixtureData->objectForKey("density"))->floatValue(); basicData.restitution = static_cast<CCString *>(fixtureData->objectForKey("restitution"))->floatValue(); basicData.isSensor = (bool)static_cast<CCString *>(fixtureData->objectForKey("isSensor"))->intValue(); if(fixtureData->objectForKey("id")) { basicData.userData = static_cast<CCString *>(fixtureData->objectForKey("id")); callbackData = static_cast<CCString *>(fixtureData->objectForKey("id"))->intValue(); } std::string fixtureType = static_cast<CCString *>(fixtureData->objectForKey("fixture_type"))->getCString(); //CCString *fixtureType = static_cast<CCString *>(fixtureData->objectForKey("fixture_type"))->getCString(); if (fixtureType == "POLYGON") { //CCDictionary *polygons = (CCDictionary *)fixtureData->objectForKey("polygons"); CCArray *polygons = (CCArray *)fixtureData->objectForKey("polygons"); //CCDictElement *polygon = NULL; CCObject *polygon = NULL; //CCDICT_FOREACH(polygons, polygon) CCARRAY_FOREACH(polygons, polygon) { FixtureDef *fix = new FixtureDef(); fix->fixture = basicData; // copy basic data fix->callbackData = callbackData; b2PolygonShape *polyshape = new b2PolygonShape(); int vindex = 0; //CCDictionary *polygonData = (CCDictionary *)polygon->getObject(); CCArray *polygonData = (CCArray *)polygon; assert(polygonData->count() <= b2_maxPolygonVertices); //CCDictElement *offset = NULL; CCObject *offset = NULL; //CCDICT_FOREACH(polygonData, offset) CCARRAY_FOREACH(polygonData, offset) { CCString *pStr = (CCString *)offset; CCPoint p = CCPointFromString(pStr->getCString()); vertices[vindex].x = (p.x / ptmRatio) ; vertices[vindex].y = (p.y / ptmRatio) ; vindex++; }
void HelloWorld::update(float dt) { CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCPoint backgroundScrollVert = ccp(-1000, 0); _backgroundNode->setPosition(ccpAdd(_backgroundNode->getPosition(), ccpMult(backgroundScrollVert, dt))); CCArray *spaceDusts = CCArray::createWithCapacity(2); spaceDusts->addObject(_spacedust1); spaceDusts->addObject(_spacedust2); for ( int ii = 0; ii <spaceDusts->count(); ii++ ) { CCSprite * spaceDust = (CCSprite *)(spaceDusts->objectAtIndex(ii)); float xPosition = _backgroundNode->convertToWorldSpace(spaceDust->getPosition()).x; float size = spaceDust->getContentSize().width; if ( xPosition < -size/2 ) { _backgroundNode->incrementOffset(ccp(spaceDust->getContentSize().width*2,0),spaceDust); } } CCArray *backGrounds = CCArray::createWithCapacity(4); backGrounds->addObject(_galaxy); backGrounds->addObject(_planetsunrise); backGrounds->addObject(_spacialanomaly); backGrounds->addObject(_spacialanomaly2); for ( int ii = 0; ii <backGrounds->count(); ii++ ) { CCSprite * background = (CCSprite *)(backGrounds->objectAtIndex(ii)); float xPosition = _backgroundNode->convertToWorldSpace(background->getPosition()).x; float size = background->getContentSize().width; if ( xPosition < -size ) { _backgroundNode->incrementOffset(ccp(2000,0),background); } } /** * Accelerometer */ float maxY = winSize.height - _ship->getContentSize().height/2; float minY = _ship->getContentSize().height/2; float diff = (_shipPointsPerSecY * dt); float newY = _ship->getPosition().y + diff; newY = MIN(MAX(newY, minY), maxY); _ship->setPosition(ccp(_ship->getPosition().x, newY)); /** * Asteroids */ float curTimeMillis = getTimeTick(); if (curTimeMillis > _nextAsteroidSpawn) { float randMillisecs = randomValueBetween(0.20, 1.0) * 1000; _nextAsteroidSpawn = randMillisecs + curTimeMillis; float randY = randomValueBetween(0.0, winSize.height); float randDuration = randomValueBetween(2.0, 10.0); CCSprite *asteroid = (CCSprite *)_asteroids->objectAtIndex(_nextAsteroid); _nextAsteroid++; if (_nextAsteroid >= _asteroids->count()) _nextAsteroid = 0; asteroid->stopAllActions(); asteroid->setPosition( ccp(winSize.width+asteroid->getContentSize().width/2, randY)); asteroid->setVisible(true); asteroid->runAction(CCSequence::create(CCMoveBy::create(randDuration, ccp(-winSize.width-asteroid->getContentSize().width, 0)), CCCallFuncN::create(this, callfuncN_selector(HelloWorld::setInvisible)), NULL // DO NOT FORGET TO TERMINATE WITH NULL (unexpected in C++) )); } /** * Collision Detection */ // Asteroids CCObject* asteroid; CCObject* shipLaser; CCARRAY_FOREACH(_asteroids, asteroid) { if ( !((CCSprite *) asteroid)->isVisible() ) continue; CCARRAY_FOREACH(_shipLasers, shipLaser) { if ( !((CCSprite *) shipLaser)->isVisible() ) continue; // Laser hits asteroid if (((CCSprite *) shipLaser)->boundingBox().intersectsRect(((CCSprite *)asteroid)->boundingBox()) ) { ((CCSprite *)shipLaser)->setVisible(false); ((CCSprite *)asteroid)->setVisible(false); _score++; continue; } } // Asteroid collides with ship if (_ship->boundingBox().intersectsRect(((CCSprite *)asteroid)->boundingBox()) ) { SimpleAudioEngine::sharedEngine()->playEffect("explosion_large.wav"); ((CCSprite *)asteroid)->setVisible(false); _ship->runAction( CCBlink::create(1.0, 9)); _lives--; } } /** * Win/Lose Detection */ if (_lives <= 0) { _ship->stopAllActions(); _ship->setVisible(false); this->setTouchEnabled(false); this->endScene(KENDREASONLOSE); } else if (curTimeMillis >= _gameOverTime) { this->endScene(KENDREASONWIN); } }
void GB2ShapeCache::addShapesWithFile(const std::string &plist) { //const char *fullName = CCFileUtils::sharedFileUtils()->fullPathForFilename(plist.c_str()).c_str(); CCDictionary *dict = CCDictionary::createWithContentsOfFile(plist.c_str()); // not triggered - cocos2dx delivers empty dict if non was found CCAssert(dict != NULL, "Shape-file not found"); CCAssert(dict->count() != 0, "plist file empty or not existing"); CCDictionary *metadataDict = (CCDictionary *)dict->objectForKey("metadata"); int format = static_cast<CCString *>(metadataDict->objectForKey("format"))->intValue(); ptmRatio = static_cast<CCString *>(metadataDict->objectForKey("ptm_ratio"))->floatValue(); CCLOG("ptmRatio = %f",ptmRatio); CCAssert(format == 1, "Format not supported"); CCDictionary *bodyDict = (CCDictionary *)dict->objectForKey("bodies"); b2Vec2 vertices[b2_maxPolygonVertices]; CCDictElement *dictElem; std::string bodyName; CCDictionary *bodyData; //iterate body list CCDICT_FOREACH(bodyDict,dictElem ) { bodyData = (CCDictionary*)dictElem->getObject(); bodyName = dictElem->getStrKey(); BodyDef *bodyDef = new BodyDef(); bodyDef->anchorPoint = CCPointFromString(static_cast<CCString *>(bodyData->objectForKey("anchorpoint"))->getCString()); CCArray *fixtureList = (CCArray*)(bodyData->objectForKey("fixtures")); FixtureDef **nextFixtureDef = &(bodyDef->fixtures); //iterate fixture list CCObject *arrayElem; CCARRAY_FOREACH(fixtureList, arrayElem) { b2FixtureDef basicData; CCDictionary* fixtureData = (CCDictionary*)arrayElem; basicData.filter.categoryBits = static_cast<CCString *>(fixtureData->objectForKey("filter_categoryBits"))->intValue(); basicData.filter.maskBits = static_cast<CCString *>(fixtureData->objectForKey("filter_maskBits"))->intValue(); basicData.filter.groupIndex = static_cast<CCString *>(fixtureData->objectForKey("filter_groupIndex"))->intValue(); basicData.friction = static_cast<CCString *>(fixtureData->objectForKey("friction"))->floatValue(); basicData.density = static_cast<CCString *>(fixtureData->objectForKey("density"))->floatValue(); basicData.restitution = static_cast<CCString *>(fixtureData->objectForKey("restitution"))->floatValue(); basicData.isSensor = (bool)static_cast<CCString *>(fixtureData->objectForKey("isSensor"))->intValue(); CCString *cb = static_cast<CCString *>(fixtureData->objectForKey("userdataCbValue")); int callbackData = 0; if (cb) callbackData = cb->intValue(); std::string fixtureType = static_cast<CCString *>(fixtureData->objectForKey("fixture_type"))->m_sString; if (fixtureType == "POLYGON") { CCArray *polygonsArray = (CCArray *)(fixtureData->objectForKey("polygons")); CCObject *dicArrayElem; CCARRAY_FOREACH(polygonsArray, dicArrayElem) { FixtureDef *fix = new FixtureDef(); fix->fixture = basicData; // copy basic data fix->callbackData = callbackData; b2PolygonShape *polyshape = new b2PolygonShape(); int vindex = 0; CCArray *polygonArray = (CCArray*)dicArrayElem; assert(polygonArray->count() <= b2_maxPolygonVertices); CCObject *piter; CCARRAY_FOREACH(polygonArray, piter) { CCString *verStr = (CCString*)piter; CCPoint offset = CCPointFromString(verStr->getCString()); vertices[vindex].x = (offset.x / ptmRatio) ; vertices[vindex].y = (offset.y / ptmRatio) ; vindex++; }