void GameLayer::initMapNode(CCNode *node) { // window size CCSize winSize = CCDirector::sharedDirector()->getWinSize(); // use batchnode to reduce rendering CCSpriteBatchNode *batchNode = CCSpriteBatchNode::create("GameScene.pvr.ccz"); node->addChild(batchNode, 0, MapBatchNodeTag); // add background CCSprite *backgroundSprite = CCSprite::createWithSpriteFrameName("Background.png"); backgroundSprite->setPosition(ccp(winSize.width/2.f, winSize.height/2.f)); batchNode->addChild(backgroundSprite); // add glass road CCSprite *glassRoadSprite = CCSprite::createWithSpriteFrameName("Road.png"); glassRoadSprite->setPosition(ccp(winSize.width/2.f, winSize.height/2.f)); batchNode->addChild(glassRoadSprite); // add monster CCSprite *monsterSprite = CCSprite::createWithSpriteFrameName("Monster.png"); batchNode->addChild(monsterSprite, 0, MapMonsterTag); // add river CCSprite *riverSprite = CCSprite::createWithSpriteFrameName("River.png"); batchNode->addChild(riverSprite, 0, MapRiverTag); // add coins for (int i = 0; i < kGameCoinCount; i ++) { CCSprite *coinSprite = CCSprite::createWithSpriteFrameName("Gold.png"); batchNode->addChild(coinSprite, 0, MapCoinStartTag + i); } }
void BattleCharacter::MapShowHPOffset(int dam) { CCSpriteBatchNode* pNumBatchNode = (CCSpriteBatchNode*)m_pMap->getChildByTag(LAYER_MAPNUMS_ID); CCArray* numSprites = NULL; if (dam<0) { numSprites = AnimationManager::instance()->CreateSizeNums(-dam,NUMS_SMALL_RED); } else { numSprites = AnimationManager::instance()->CreateSizeNums(dam,NUMS_SMALL_BLACK); } unsigned int count = numSprites->count(); //计算当前前数字个数,决定显示位置的偏移量。当个数为奇数时,不做办个数字的偏移。当数字为偶数时,需要向右偏移半个数字精灵的图片宽度。 float distance = NUMS_SMALL_DISTANCE; float half = count%2==0?0:distance/2; for(unsigned int index = 0;index<count;index++) { CCSprite* numSprite = (CCSprite*)numSprites->objectAtIndex(index); pNumBatchNode->addChild(numSprite,MAX_LAYER_ZORDER); numSprite->setPosition(ccp(GetMapPositionX()+half+(count/2-index)*distance,GetMapPositionY())); numSprite->runAction(CCSequence::createWithTwoActions(CCMoveBy::create(NUMS_MAPFALL_DUR,ccp(0,SQUARE_LENTH/2)),CCCallFuncND::create(this,callfuncND_selector(AnimationManager::RemoveAniamationSprite),(void*)numSprite))); } }
void SpriteBatchNodeTestPage::loadUI() { setTouchEnabled(true); setTouchMode(kCCTouchesOneByOne); auto winSize = CocosWindow::size(); auto origin = CocosWindow::origin(); const std::string pic("Images/grossini_dance_01.png"); size_t num(1000); /*for (size_t i=0; i<num; ++i) { auto dance = CCSprite::create(pic.c_str()); CCPoint pos; pos.x = winSize.width * CCRANDOM_0_1(); pos.y = winSize.height * CCRANDOM_0_1(); dance->setPosition(pos); addChildRaw(dance); }*/ CCSpriteBatchNode *batch = CCSpriteBatchNode::create(pic.c_str()); for (size_t i=0; i<num; ++i) { auto dance = CCSprite::createWithTexture(batch->getTexture()); CCPoint pos; pos.x = winSize.width * CCRANDOM_0_1(); pos.y = winSize.height * CCRANDOM_0_1(); dance->setPosition(pos); batch->addChild(dance); } ADD_CHILD(batch); }
bool Recipe30::init() { if ( !RecipeBase::init() ) { return false; } CCSize size = CCDirector::sharedDirector()->getWinSize(); CCSpriteBatchNode* pBatchNode = CCSpriteBatchNode::create("recipe30_uhhoi.png"); this->addChild(pBatchNode); for (int i=0; i<300; i++) { CCSprite* sprite = CCSprite::createWithTexture(pBatchNode->getTexture()); float x = CCRANDOM_0_1()*size.width; float y = CCRANDOM_0_1()*size.height; sprite->setPosition(ccp(x, y)); pBatchNode->addChild(sprite); CCFadeOut* fade = CCFadeOut::create(CCRANDOM_0_1()*10.0f); sprite->runAction(fade); } return true; }
bool T08CCSpriteBatchNode::init() { if (!BaseLayer::init()) return false; CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCPoint ptCenter = ccp(winSize.width / 2, winSize.height / 2); /* CCSpriteBatchNode是一个容器,只能包容CCSprite对象,要求这些精灵来自同一个纹理 */ CCSpriteBatchNode* pBatch = CCSpriteBatchNode::create("CloseNormal.png"); addChild(pBatch); pBatch->setTag(10); CCSprite *pSprite = CCSprite::createWithTexture(pBatch->getTexture()); pBatch->addChild(pSprite); pSprite->setPosition(ptCenter); setTouchEnabled(true); setTouchMode(kCCTouchesOneByOne); return true; }
void Box2DTestLayer::addNewSpriteWithCoords(CCPoint p) { //UXLOG(L"Add sprite %0.2f x %02.f",p.x,p.y); CCSpriteBatchNode* sheet = (CCSpriteBatchNode*)getChildByTag(kTagSpriteManager); //We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is //just randomly picking one of the images int idx = (CCRANDOM_0_1() > .5 ? 0:1); int idy = (CCRANDOM_0_1() > .5 ? 0:1); CCSprite *sprite = sheet->createSpriteWithRect( CCRectMake(32 * idx,32 * idy,32,32)); sheet->addChild(sprite); sprite->setPosition( CCPointMake( p.x, p.y) ); // Define the dynamic body. //Set up a 1m squared box in the physics world b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO); bodyDef.userData = sprite; b2Body *body = world->CreateBody(&bodyDef); // Define another box shape for our dynamic body. b2PolygonShape dynamicBox; dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); }
void GameLayer::initPlayer() { CCSpriteFrameCache* frameCache = CCSpriteFrameCache::sharedSpriteFrameCache(); frameCache->addSpriteFramesWithFile("LuckyFlying.plist"); CCSpriteBatchNode* pigeonFlightSheet = CCSpriteBatchNode::create("LuckyFlying.png"); addChild(pigeonFlightSheet, 3); CCArray* pigeonFrames = new CCArray; for ( int i = 2; i <= 4; i++) { CCString* filename = CCString::createWithFormat("lucky_flying_0000%d.png", i); CCSpriteFrame* frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(filename->getCString()); pigeonFrames->addObject(frame); } CCAnimation* flightAnim = CCAnimation::createWithSpriteFrames(pigeonFrames, 0.1); pigeonSprite = CCSprite::createWithSpriteFrameName("lucky_flying_00002.png"); //pigeonSprite->setScale(0.5f); pigeonSprite->setPosition(ccp(SCREEN_WIDTH/2 - 500, SCREEN_WIDTH*3 + 250)); CCAction* flightAction = CCRepeatForever::create(CCAnimate::create(flightAnim)); pigeonSprite->runAction(flightAction); pigeonFlightSheet->addChild(pigeonSprite, 3); schedule(schedule_selector(GameLayer::tick1), 0.10f); schedule(schedule_selector(GameLayer::tick2), 0.03f); }
//------------------------------------------------------------------------------ // // void CMiniGameCatchLayer::AddCartchSprite(CCPoint p) { //UXLOG(L"Add sprite %0.2f x %02.f",p.x,p.y); CCSpriteBatchNode *mgr = (CCSpriteBatchNode*)getChildByTag( kTagSpriteManager ); int index = 1 + (int)(CCRANDOM_0_1() * 11); int pixScale = 1; #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if( CDevice::GetDeviceType() == "iPad" ) { pixScale = 2; } #endif CCRect rect( ( index % 4) * 32 * pixScale, index / 4 * 32 * pixScale ,32 * pixScale, 32 * pixScale ); CCSprite *sprite = CCSprite::spriteWithBatchNode( mgr, rect ); // addChild(sprite, MINIGAME_LAYER_BEGIN); sprite->setPosition( CCPointMake( p.x, p.y) ); sprite->setTag( index ); mgr->addChild( sprite ); //sprite->setAnchorPoint(ccp( 0,0 )); // Define the dynamic body. //Set up a 1m squared box in the physics world b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO); bodyDef.userData = sprite; b2Body *body = world->CreateBody(&bodyDef); // Define another box shape for our dynamic body. b2PolygonShape dynamicBox; dynamicBox.SetAsBox(32.0f/ PTM_RATIO / 2.0f, 32.0f/ PTM_RATIO / 2.0f);//These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 5.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); CCSize screenSize = CCDirector::sharedDirector()->getWinSize(); b2Vec2 d; srand( GetCurrentSeconds() ); d.Set( rand() % 10 * screenSize.width / 10.f, screenSize.height + screenSize.height ); d.Normalize(); b2Vec2 F = 80 * d; body->ApplyForce(F,d); }
void Object::performAnimation(string name, SEL_CallFunc func){ if (this->getCurrentObjectState() == ObjectStateDead && name.compare("Dead") != 0) { return; } CCSpriteBatchNode *currentSpriteBatchNode = m_pobBatchNode; CCSpriteBatchNode *newSpriteBatchNode = NULL; // Get the action pair by key name CCArray *actionPair = (CCArray *)actionsHashes->objectForKey(name); // If the action pair does not exist, return early if (!actionPair) { return; } newSpriteBatchNode = (CCSpriteBatchNode *)actionPair->objectAtIndex(1); ActionNode *actionNode = (ActionNode *)actionPair->objectAtIndex(0); this->stopActionByTag(ACTION_ANIMATION_TAG); // If required spriteBatchNode is different from current, replace it if (currentSpriteBatchNode != newSpriteBatchNode) { this->removeFromParentAndCleanup(false); this->setTexture(actionNode->getFirstSpriteFrame()->getTexture()); this->setTextureRect(actionNode->getFirstSpriteFrame()->getRect()); newSpriteBatchNode->addChild(this); } if (func != NULL) { CCAssert(dynamic_cast<CCRepeatForever*>(actionNode->getAnimation()) == NULL, "Not able to call function for CCRepeatForever action."); // Create animation followed by a function call CCSequence *seq = CCSequence::createWithTwoActions(actionNode->getAnimation(), CCCallFunc::create(this, func)); seq->setTag(ACTION_ANIMATION_TAG); this->runAction(seq); } else { // Run the action actionNode->getAnimation()->setTag(ACTION_ANIMATION_TAG); this->runAction(actionNode->getAnimation()); } // Run AI in this action { if (actionPair->count() > 2) { CCArray *AIActions = (CCArray *)actionPair->objectAtIndex(2); CCLOG("%s is running AI, total AIAction count: %d", identifier.c_str(), AIActions->count()); for (int i = 0; i < AIActions->count(); i++) { CCAction *action = (CCAction*)AIActions->objectAtIndex(i); this->runAction(action); } } } }
void GameLayer::initBarrierNode(CCNode *node) { // window size CCSize winSize = CCDirector::sharedDirector()->getWinSize(); // use batchnode to reduce rendering CCSpriteBatchNode *batchNode = CCSpriteBatchNode::create("GameScene.pvr.ccz"); node->addChild(batchNode, 0, MapBatchNodeTag); // add barrier CCSprite *barrierSprite = CCSprite::createWithSpriteFrameName("Barrier.png"); batchNode->addChild(barrierSprite, 0, MapBarrierTag); }
void SoulPrev::createFish(const CCPoint& point) { //use CCSpriteBachNode to draw texture CCTexture2D* texture = CCTextureCache::sharedTextureCache()->textureForKey("fish.png"); CCSpriteBatchNode* spbatch = CCSpriteBatchNode::createWithTexture(texture); spbatch->setPosition(ccp(0, 0)); this->addChild(spbatch); CCSprite* sprite = CCSprite::createWithSpriteFrameName("hudieyu_72.png"); sprite->setPosition(point); sprite->setPosition(point); spbatch->addChild(sprite); }
bool T08CCSpriteBatchNode::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCSpriteBatchNode* pBatch = (CCSpriteBatchNode*)getChildByTag(10); for (int i = 0; i < 1000; i++) { CCSprite* pSprite = CCSprite::create("CloseNormal.png"); pBatch->addChild(pSprite); pSprite->setPosition(ccp(CCRANDOM_0_1()*winSize.width, CCRANDOM_0_1()*winSize.height)); } return true; }
CCNode *APSSprite::createNode() { CCNode *node = APSGraphic::createNode(); APSImageHolder *ih = this->getImageHolder(); CCSize contentSize; CCSize targetSize = APSPlatform::sharedPlatform()->convertSizeToPixels(this->getSize()); if (ih) { this->m_spriteNode = new CCSprite; if (this->getIsAnimatable()) { // Create animation sprite APSSpriteSheetHolder *sh = (APSSpriteSheetHolder *)ih; CCSpriteFrame *spriteFrame = sh->getCCSpriteFrameAtIndex(((APSGraphicGroup *)this->getParent())->getDisplayedFrameIndex()); #if COCOS2D_VERSION >= 0x00020000 CCSpriteBatchNode *spriteSheet = CCSpriteBatchNode::createWithTexture(ih->getTexture(), sh->getCount()); #else CCSpriteBatchNode *spriteSheet = CCSpriteBatchNode::batchNodeWithTexture(ih->getTexture(), sh->getCount()); #endif//APS_SKIP this->m_node->addChild(spriteSheet); this->m_spriteNode->initWithSpriteFrame(spriteFrame); spriteSheet->addChild(this->m_spriteNode); CCSize size = this->m_spriteNode->getContentSize(); contentSize = APSPlatform::sharedPlatform()->convertSizeToPixels(size); } else { // Check if there is a sprite frame in sprite frame cache. CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(this->getImageHolder()->getRuntimeFilename().c_str()); if (frame) { // Use the sprite frame this->m_spriteNode->initWithSpriteFrame(frame); contentSize = frame->getOriginalSizeInPixels(); node->addChild(this->m_spriteNode); } else { // Normal sprite this->m_spriteNode->initWithTexture(ih->getTexture()); contentSize = ih->getTexture()->getContentSizeInPixels(); node->addChild(this->m_spriteNode); } } // scale the sprite to match the sizes of texture and sprite this->m_spriteNode->setScaleX(targetSize.width/contentSize.width); this->m_spriteNode->setScaleY(targetSize.height/contentSize.height); } return node; }
void EnemyPlaneLayer::loadEnemys() { //当一批飞机全部添加后,此批敌机没有被消灭干净前,不再增加下批敌机 if((EnemyPlane::_enemyPlanes.count() > 0)){ delayTimerCallLoadEnemys(1.0f); return; } static int batchIndex = 0; //第几批敌机 float aircraftTimeSum = 0; //每批敌机出场时间和 //当前批敌机数组 CCArray* batchEnemys = dynamic_cast<CCArray*>(m_enemyPlanesArray.objectAtIndex(batchIndex)); CCObject* obj = NULL; CCARRAY_FOREACH(batchEnemys,obj){ CCDictionary* enemyDict = dynamic_cast<CCDictionary*>(obj); //当前敌机属性字典,获取敌机出场时间 GameObjectPool* factory = EnemyPlaneFactory::shareEnemyPlaneFactory(); EnemyPlane* enemyPlane = NULL; if(factory) { enemyPlane = dynamic_cast<EnemyPlane*>(factory->getObject(enemyDict)); //调式用的全局敌机变量 _enemyPlane = enemyPlane; //设置被碰撞粒子效果的文件名 enemyPlane->setHitParticleName(NORMAL_HIT_PARTICLE_PLIST); //粒子效果的父层需要是非批渲染层 enemyPlane->setBatchParticleNodesParent(this); //计算出场时间之和 aircraftTimeSum += enemyPlane->getAircraftTime(); //计算出场位置 srand((unsigned) time(NULL)); float t = enemyPlane->getScale(); int t1 = rand(); float widthRange = CCDirector::sharedDirector()->getWinSize().width - enemyPlane->boundingBox().size.width * enemyPlane->getScale(); float startPositionX = enemyPlane->boundingBox().size.width / 2 * enemyPlane->getScale() + rand() % int(widthRange); float startPositionY = CCDirector::sharedDirector()->getWinSize().height + enemyPlane->boundingBox().size.height * enemyPlane->getScale() + 10; startPositionX = CCDirector::sharedDirector()->getWinSize().width / 2; enemyPlane->setPosition(ccp(startPositionX,startPositionY)); enemyPlane->prepareFly(); CCSpriteBatchNode* batchNode = AppConfig::shareAppConfig()->getGlobalBatchNode(); enemyPlane->setBullteFlySpace(batchNode); batchNode->addChild(enemyPlane,ENEMY_PLANE_ZORDER); } }
void GameLayer::_initPlatform() { CCRect rect; switch((int)CCRANDOM_0_1() * 2) { case 0: rect = CCRectMake(608, 64, 102, 36); break; case 1: rect = CCRectMake(608, 128, 90, 32); break; } CCSpriteBatchNode* batchNode = dynamic_cast<CCSpriteBatchNode*>(getChildByTag(kSpriteManager)); CCSprite* platform = CCSprite::createWithTexture(batchNode->getTexture(), rect); batchNode->addChild(platform, 3, currentPlatformTag); }
void HelloWorld::addPhysicSprite() { #if CC_ENABLE_CHIPMUNK_INTEGRATION // Use batch node. Faster CCSpriteBatchNode *parent = CCSpriteBatchNode::create(s_SpinPea, 100); m_pSpriteTexture = parent->getTexture(); addChild(parent, 100, kTagParentNode); CCPoint pos = ccp(200,200); int posx, posy; CCNode *parent = getChildByTag(kTagParentNode); posx = CCRANDOM_0_1() * 200.0f; posy = CCRANDOM_0_1() * 200.0f; posx = (posx % 4) * 85; posy = (posy % 3) * 121; int num = 4; cpVect verts[] = { cpv(-24,-54), cpv(-24, 54), cpv( 24, 54), cpv( 24,-54), }; cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero)); body->p = cpv(pos.x, pos.y); cpSpaceAddBody(m_pSpace, body); cpShape* shape = cpPolyShapeNew(body, num, verts, cpvzero); shape->e = 0.5f; shape->u = 0.5f; cpSpaceAddShape(m_pSpace, shape); CCPhysicsSprite *sprite = CCPhysicsSprite::createWithTexture(m_pSpriteTexture, CCRectMake(posx, posy, 85, 121)); parent->addChild(sprite,50); sprite->setCPBody(body); sprite->setPosition(pos); #endif }
bool DefaultLayer::init() { if (!CCLayer::init()) return false; // ask director the window size CCSize window_size = CCDirector::sharedDirector()->getWinSize(); CCImage* temp_img = new CCImage(); temp_img->initWithImageFile("atlas.png"); CCTexture2D* texture = new CCTexture2D(); texture->initWithImage(temp_img); texture->autorelease(); delete temp_img; // this will have a capacity for 4 sprites instead of the default which is 20 CCSpriteBatchNode* batch = CCSpriteBatchNode::createWithTexture(texture, 4); // Since I don't have HD versions of the image but I've set enableRetinaDisplay to true, the framework // is using a scaling factor of 2 to divide the image by. This is because it thinks the image was from the low resolution // version, which would mean that running in retina (i.e. 2x larger screen) should make the image look half as big. By calling // getContentSize over getContentSizeInPixels I'm getting the size of the image as it is represented for the appropriate // draw mode. If I actually had HD art, I believe I could just call getContentSizeInPixels and that they'd both be the same. CCSize tex_size(texture->getContentSize()); for (int i = 0; i < 4; i++) { CCSprite* sprite = CCSprite::create(); // The texture rect coords are luckily normal and just like a Photoshop canvas CCRect r((i % 2) == 0 ? 0 : tex_size.width / 2.0f, (i / 2) == 0 ? 0 : tex_size.height / 2.0f, tex_size.width/2.0f, tex_size.height/2.0f); sprite->initWithTexture(texture, r); sprite->setPosition(ccp(sprite->getContentSize().width / 2.0f + (i % 2)*200, sprite->getContentSize().height + (i/2)*150)); batch->addChild(sprite); } addChild(batch); return true; }
void HomeScene::__initLighting() { const int deg = 30; CCSpriteBatchNode *pLightingNode = CCSpriteBatchNode::createWithTexture(SPRITE("*****@*****.**")->getTexture()); for(int i=0; i<6; i++) { CCSprite *light = SPRITE("*****@*****.**"); light->setRotation(i*deg); light->setScale(2); pLightingNode->addChild(light); } ccBlendFunc cbl = {GL_DST_COLOR, GL_ONE}; pLightingNode->setBlendFunc(cbl); pLightingNode->setPosition(VisibleRect::center()); addChild(pLightingNode); //使光芒开始旋转 CCRotateBy *rotateAct = CCRotateBy::create(1,30); pLightingNode->runAction(CCRepeatForever::create(rotateAct)); }
//与ShowMapDam实现方案相同,只是将字体换为黑色---暂定 void BattleCharacter::RefreshPlayer() { if (m_nForceFlag!=FORCE_PLAYER) { return; } CCArray* numSprites = AnimationManager::instance()->CreateSizeNums(m_nExpGot,NUMS_SMALL_BLACK); CCSpriteBatchNode* pNumBatchNode = (CCSpriteBatchNode*)m_pMap->getChildByTag(LAYER_MAPNUMS_ID); unsigned int count = numSprites->count(); float distance = NUMS_SMALL_DISTANCE; float half = count%2==0?0:distance/2; for(unsigned int index = 0;index<count;index++) { CCSprite* numSprite = (CCSprite*)numSprites->objectAtIndex(index); pNumBatchNode->addChild(numSprite,MAX_LAYER_ZORDER); numSprite->setPosition(ccp(GetMapPositionX()+half+(count/2-index)*distance,GetMapPositionY()+SQUARE_LENTH/2)); numSprite->runAction(CCSequence::create(CCMoveBy::create(NUMS_MAPFALL_DUR,ccp(0,-SQUARE_LENTH/2)),CCCallFuncND::create(this,callfuncND_selector(AnimationManager::RemoveAniamationSprite),(void*)numSprite), CCCallFuncND::create(this,callfuncND_selector(BattleCharacter::ExpForLevelCallBack),NULL),NULL)); } }
bool BatchManager::addItem(GameEntitySprite* entity, CCNode* layer, CCPoint parallax) { char* name = entity->getNodeInfo().texture; bool found = false; std::list<BatchManagerItem*>::iterator item; for (item = items.begin(); item != items.end(); item++) { BatchManagerItem* i = dynamic_cast<BatchManagerItem*>(*item); if (!i) continue; char* iName = i->sprite->getNodeInfo().texture; if (xmlStrcasecmp((xmlChar*) iName, (xmlChar*) name) == 0 && parallax.equals(i->parallax) ) { found = true; break; } } // Add sprite to batch if exists, or create new batch if (found) (*item)->batchNode->addChild(entity->getSprite()); else { BatchManagerItem* mgr = new BatchManagerItem(); CCSpriteBatchNode *node = CCSpriteBatchNode::create(name); mgr->batchNode = node; mgr->sprite = entity; mgr->parallax = parallax; node->addChild(entity->getSprite()); items.push_front(mgr); layer->addChild(mgr->batchNode); } return false; }
void HelloWorld::addNewSpriteX(float x, float y) { int posx, posy; CCSpriteBatchNode *batch = (CCSpriteBatchNode*) getChildByTag(kTagBatchNode); posx = (CCRANDOM_0_1() * 200); posy = (CCRANDOM_0_1() * 200); posx = (posx % 4) * 85; posy = (posy % 3) * 121; CCSprite *sprite = CCSprite::spriteWithBatchNode(batch, CCRectMake(posx, posy, 85, 121)); batch->addChild(sprite); sprite->setPosition(ccp(x, y)); int num = 4; cpVect verts[] = { cpv(-24,-54), cpv(-24, 54), cpv( 24, 54), cpv( 24,-54), }; cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpv(0, 0))); // TIP: // since v0.7.1 you can assign CGPoint to chipmunk instead of cpVect. // cpVect == CGPoint body->p = cpv(x, y); cpSpaceAddBody(space, body); cpShape* shape = cpPolyShapeNew(body, num, verts, cpv(0, 0)); shape->e = 0.5f; shape->u = 0.5f; shape->data = sprite; cpSpaceAddShape(space, shape); }
CCSprite* DiggingWorld::s_createTileSprite( const char *pRectName, unsigned int nColumn, unsigned int nHeight, float fScaleX, float fScaleY, int nZorder ) { LayerGaming *pLayerGaming = LayerGaming::sharedLayerGaming(); CCSpriteBatchNode *pBatchNode = pLayerGaming->getTilesBatchNode(); DiggingWorld *pDiggingWorld = DiggingWorld::sharedDiggingWorld(); CCSprite *pRetSprite = NULL; CCRect RECT_TILE = LuaHelper::s_getRectVar( pRectName ); pRetSprite = CCSprite::createWithTexture( pBatchNode->getTexture(), RECT_TILE ); pBatchNode->addChild( pRetSprite, nZorder ); //¼ÆËãspriteµÄλÖà float fSoilSpriteX = 0.0f; float fSoilSpriteY = 0.0f; pDiggingWorld->convertToGLCoordinate( nHeight, nColumn, fSoilSpriteX, fSoilSpriteY ); float fTileSize = pDiggingWorld->getTileSize(); pRetSprite->setScaleX( fTileSize / RECT_TILE.size.width * fScaleX ); pRetSprite->setScaleY( fTileSize / RECT_TILE.size.height * fScaleY ); pRetSprite->setPosition( ccp( fSoilSpriteX, fSoilSpriteY ) ); return pRetSprite; }
void Entiles::initFiles(const char *pszFileName) { CC_SAFE_RELEASE_NULL(m_sprite); m_sprite = CCSprite::createWithSpriteFrameName("blank.png"); m_sprite->setAnchorPoint(ccp(0.5,0.5)); m_sprite->setPosition(CCPointZero); m_sprite->setOpacity(0); //CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache(); //CCSpriteBatchNode *sheet = CCSpriteBatchNode::create("sprite/gongbin.png"); //cache->addSpriteFramesWithFile("sprite/gongbin.plist"); //SplashLayer->addChild(sheet); //CCSpriterX *animator; //animator = CCSpriterX::create("sprite/gongbin.SCML"); CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache(); CCSpriteBatchNode *sheet = CCSpriteBatchNode::create(CCString::createWithFormat("%s.png",pszFileName)->getCString()); cache->addSpriteFramesWithFile(CCString::createWithFormat("%s.plist",pszFileName)->getCString()); m_animator = CCSpriterX::create(CCString::createWithFormat("%s.SCML",pszFileName)->getCString()); m_animator->setAnchorPoint(ccp(0.5,0.5)); m_animator->setPosition(ccp(-48,92)); // animator->setScale(0.8f); // animator->PlayAnim("Idle"); sheet->addChild(m_animator); m_sprite->addChild(sheet); addChild(m_sprite); m_sprite->setTag(9); psz = pszFileName; }
GameLayer::GameLayer() { gameSuspended = true; isGameOver = false; fuelInTank = 3600; // one minute worth CCSpriteBatchNode* batchNode = dynamic_cast<CCSpriteBatchNode*>(getChildByTag(kSpriteManager)); // Initialize all the platforms. Really? They predraw all the platforms?? _initPlatforms(); // We don't need a packed sprite, we can pick individual textures. Here we are getting the sprite for the bird CCSprite* bird = CCSprite::createWithTexture(batchNode->getTexture(), CCRectMake(608, 16, 44, 32)); batchNode->addChild(bird, 4, kBird); // add the exit arrow CCSprite* exit = CCSprite::create("exit_arrow.png"); exit->setTag(kExit); exit->setVisible(false); addChild(exit); CCSize landscapeSize = CCDirector::sharedDirector()->getVisibleSize(); CCSize visibleSize = CCSize(landscapeSize.width, landscapeSize.height); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); pHealthSprite = CCSprite::create("health_bar.png"); //pHealthSprite->setPosition(ccp(origin.x + 10, visibleSize.height - 20)); pHealthSprite->setAnchorPoint(ccp(0.0, 0.0)); //pHealthSprite->setScaleY(0.02); //pHealthSprite->setScaleX(100); pHealthBar = CCProgressTimer::create(pHealthSprite); pHealthBar->setScale(0.5, 0.5); pHealthBar->setType(kCCProgressTimerTypeBar); //pHealthBar->setMidpoint(ccp(0,0)); pHealthBar->setBarChangeRate(ccp(1,0)); pHealthBar->setPercentage(100); pHealthBar->setPosition(ccp(origin.x+10, visibleSize.height - 20)); this->addChild(pHealthBar); CCSprite* bonus; // the bonus sprites which say 5, 10 etc can be picked from here for(int i = 0; i < kNumBonuses; i++) { bonus = CCSprite::createWithTexture(batchNode->getTexture(), CCRectMake(608 + i * 32, 256, 25, 25)); batchNode->addChild(bonus, 4, kBonusStartTag + i); bonus->setVisible(false); } // TODO: read the sprite for the Exit door - add the tag "Exit to it" CCLabelBMFont* scoreLabel = CCLabelBMFont::create("0", "bitmapFont.fnt"); addChild(scoreLabel, 5, kScoreLabel); scoreLabel->setPosition(ccp(160, 430)); _startGame(); scheduleUpdate(); // We don't want touch interaction setTouchEnabled(false); setAccelerometerEnabled(true); }
bool CMainSelect::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } this->setTouchEnabled(true); // 创建背景 CCSize size = CCDirector::sharedDirector()->getWinSize(); CCSprite* backgroud = CCSprite::create("mainsel/bg.png"); backgroud->setPosition( ccp(size.width/2, size.height/2) ); this->addChild(backgroud); // 按钮 CCMenuItemImage *pLack = CCMenuItemImage::create("mainsel/lackNor.png", "mainsel/lackSel.png", this, menu_selector(CMainSelect::lakeCallback) ); CCMenuItemImage *pForest = CCMenuItemImage::create("mainsel/forestNor.png", "mainsel/forestSel.png", this, menu_selector(CMainSelect::forestCallback) ); CCMenuItemImage *pDesert = CCMenuItemImage::create("mainsel/desertNor.png", "mainsel/desertSel.png", this, menu_selector(CMainSelect::desertCallback) ); CCMenuItemImage *pPrairie = CCMenuItemImage::create("mainsel/prairieNor.png", "mainsel/prairieSel.png", this, menu_selector(CMainSelect::prairieCallback) ); pLack->setPosition( ccp(171, 437) ); pForest->setPosition( ccp(539, 401) ); pDesert->setPosition( ccp(864, 411) ); pPrairie->setPosition( ccp(392, 208) ); CCMenu* pMenu = CCMenu::create(pLack, pForest, pDesert, pPrairie, NULL); pMenu->setPosition( CCPointZero ); this->addChild(pMenu, 1); // 创建sprite sheet CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("mainsel/jingyu.plist"); CCSpriteBatchNode *spriteSheet = CCSpriteBatchNode::create("mainsel/jingyu.png"); this->addChild(spriteSheet); // 创建对象 CCSprite *sprite = CCSprite::createWithSpriteFrameName("jingyu01.png"); sprite->setPosition(ccp(920,220)); spriteSheet->addChild(sprite, 0); CCArray *arrShang = CCArray::create(); // 动画帧数组 for(int i=1; i<=8; ++i) { CCString *name = CCString::createWithFormat("jingyu%02d.png", i); arrShang->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name->getCString())); } CCArray *arrPeng = CCArray::create(); // 动画帧数组 for(int i=9; i<=11; ++i) { CCString *name = CCString::createWithFormat("jingyu%02d.png", i); arrPeng->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name->getCString())); } CCArray *arrPengRev = CCArray::createWithArray(arrPeng); arrPengRev->reverseObjects(); arrPeng->addObjectsFromArray(arrPengRev); CCFiniteTimeAction *delay = CCDelayTime::create(1); CCAnimate* anShang = CCAnimate::create(CCAnimation::createWithSpriteFrames(arrShang, 0.25)); CCAnimate* anPeng = CCAnimate::create(CCAnimation::createWithSpriteFrames(arrPeng, 0.15)); sprite->runAction(CCRepeatForever::create((CCActionInterval*)CCSequence::create(anShang, delay, anPeng,anPeng, anPeng, anPeng, anPeng, anShang->reverse(),delay,delay,delay,NULL))); return true; }
bool ToTextLayer::DerLoadImg(Script* ts){ //meta const char* filename = ts->getstring("content"); // TO Change: // x <标志是否为切换. // tag <4001左边 4002右边 int x,y; int tag = ts->getint("tag"); int flag = ts->getint("flag"); static int last = 0; switch (flag) { case -1: //Grey it { TxTajie* tcs = (TxTajie*)getChildByTag(tag); if(tcs) { tcs->f_SetGrey(true); CCLog(">[GS]:gray the tj:%d",tag); } break; } case 1: // 0:change the color; { //[0803] CCLog(">[GS]change color:fade-%d,light-%d",last,tag); TxTajie* tcs = (TxTajie*)getChildByTag(last); if(last != 0&&tcs) { tcs->f_SetGrey(true); //[0803]CCLog(">[GS]:fade succes"); } tcs = (TxTajie*)getChildByTag(tag); if(tcs) { tcs->f_SetGrey(false); CCLog(">[GS]:Light tcs:%d", tag); } last = tag; return true; } case 2: // 2:载入动画 { x = ts->getfloat("x"); y = ts->getfloat("y"); removeChildByTag(tag); string name = ts->getstring("name"); CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache(); GameManager::sharedLogicCenter()->f_cachetest(CCString::createWithFormat("%s.png",filename)->getCString()); CCSpriteBatchNode *sheet = CCSpriteBatchNode::create(CCString::createWithFormat("%s.png",filename)->getCString()); cache->addSpriteFramesWithFile(CCString::createWithFormat("%s.plist",filename)->getCString()); CCSpriterX* m_animator = CCSpriterX::create(CCString::createWithFormat("%s.SCML",filename)->getCString()); m_animator->setPosition(ccp(x,y)); m_animator->setAnchorPoint(CCPoint(0.5,0.5)); m_animator->setTag(tag); m_animator->setRotation(ts->getfloat("angel")); float scalex = ts->getfloat("scalex"); float scaley = ts->getfloat("scaley"); //if(scalex != 0) // m_animator->setScaleX(scalex); //if(scaley != 0) // m_animator->setScaleY(scaley); if(scalex != 0) { m_animator->setScale(scalex); //[0803]CCLog(">Scale."); } int zorder = ts->getint("zorder"); TagMap[name] = tag; PathMap[name] = filename; m_animator->PlayAnim(ts->getstring("animate"),ts->getint("repeat")); sheet->addChild(m_animator); addChild(sheet,ts->getint("zorder"),tag); break; } default: { x = ts->getfloat("x"); y = ts->getfloat("y"); if(y == 0) y = 180; string name = ts->getstring("name"); removeChildByTag(tag); GameManager::sharedLogicCenter()->f_cachetest(filename); //读入缓存文件,如果文件未缓存而filename不是本地文件,将会出现错误。 TxTajie* t_cs = TxTajie::create(filename); t_cs->setPosition(ccp(x,y)); t_cs->setAnchorPoint(CCPoint(0.5,0.5)); t_cs->setTag(tag); float aa = ts->getfloat("angel"); if(aa != 0) t_cs->setRotation(aa); int alpha = ts->getint("alpha"); if(alpha == 0) alpha = 255; t_cs->setOpacity(alpha); // Change default to No. If more is need, change the x flag. t_cs->setScale(0.8); //[0803]CCLog(">[GS]:Loading..."); int zorder = ts->getint("zorder"); addChild(t_cs,ts->getint("zorder")); if(zorder == 0 && ts->getint("link") == 0){ t_cs->f_SetGrey(true); CCLog(">[GS]:Load and grey:%d",tag); } if(ts->getint("link") == 1) { last = tag; //[0803]CCLog(">[GS]:Load and remain:%d",tag); } int tFlip = ts->getint("flip"); if (tFlip) t_cs->setFlipX(true); TagMap[name] = tag; PathMap[name] = filename; return true; break; } } //int x = ts->getfloat("x"); //int y = ts->getfloat("y"); //int tag = ts->getint("tag"); //string name = ts->getstring("name"); //removeChildByTag(tag); //GameManager::sharedLogicCenter()->f_cachetest(filename); //读入缓存文件,如果文件未缓存而filename不是本地文件,将会出现错误。 //CCSprite* tmp = CCSprite::create(filename); //tmp->setPosition(ccp(x,y)); //tmp->setAnchorPoint(CCPoint(0.5,0.5)); //tmp->setTag(tag); //tmp->setRotation(ts->getfloat("angel")); //addChild(tmp); //TagMap[name] = tag; //PathMap[name] = filename; return true; }
bool GameMain::init(){ if(!CCLayer::init()){ return false; } CCSpriteFrameCache* frameCache = CCSpriteFrameCache::sharedSpriteFrameCache(); frameCache->addSpriteFramesWithFile((sceneDir+"mainscene1-hd.plist").c_str()); CCSpriteBatchNode* mainSceneBatch = CCSpriteBatchNode::createWithTexture(SPRITE(mainbg.png)->getTexture()); addChild(mainSceneBatch); //背景图片 CCSprite* mainBg = SPRITE(mainbg.png); CCPoint centerPoint = ccp(winSize.width/2,winSize.height/2); mainBg->setPosition(centerPoint); mainSceneBatch->addChild(mainBg); //云彩 CCSprite* cloud1 = SPRITE(cloud1.png); CCSprite* cloud2 = SPRITE(cloud2.png); cloud1->setPosition(ccp(-100,winSize.height-100)); cloud2->setPosition(ccp(-500,winSize.height-200)); CCActionInterval* cloud1Move = CCMoveTo::create(70,ccp(1700,winSize.height-100)); CCActionInterval* cloud2Move = CCMoveTo::create(70,ccp(1300,winSize.height-200)); cloud1->runAction(cloud1Move); cloud2->runAction(cloud2Move); cloud1->setColor(ccWHITE); cloud2->setColor(ccWHITE); ccBlendFunc bf = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA}; mainSceneBatch->setBlendFunc(bf); cloud1->setBlendFunc(bf); cloud2->setBlendFunc(bf); mainSceneBatch->addChild(cloud1); mainSceneBatch->addChild(cloud2); carrotNode = CCNode::create(); //萝卜 CCSprite* carrot = SPRITE(carrot.png); carrot->setAnchorPoint(ccp(0.5,0)); carrot->setPosition(CCPointZero); CCPoint leafPoint = ccp(0,carrot->getContentSize().height-50); //leaf CCSprite* carrotLeaf1 = SPRITE(leaf-1.png); CCSprite* carrotLeaf2 = SPRITE(leaf-2.png); CCSprite* carrotLeaf3 = SPRITE(leaf-3.png); carrotLeaf1->setAnchorPoint(ccp(1,0)); carrotLeaf2->setAnchorPoint(ccp(0.5,0)); carrotLeaf3->setAnchorPoint(ccp(0,0)); carrotLeaf1->setPosition(leafPoint); carrotLeaf2->setPosition(leafPoint); carrotLeaf3->setPosition(leafPoint); carrotNode->addChild(carrotLeaf1); carrotNode->addChild(carrotLeaf3); carrotNode->addChild(carrotLeaf2); carrotNode->addChild(carrot); carrotNode->setPosition(ccp(centerPoint.x,centerPoint.y-50)); carrotNode->setScale(0); CCActionInterval* scaleAction = CCScaleTo::create(0.3,1,1); CCActionInterval* delayRun = CCDelayTime::create(0.3); CCSequence* carrotNodeSeq = CCSequence::create(delayRun,scaleAction,NULL); addChild(carrotNode); //Logo图片 CCSprite* mainBg_CN = SPRITE(mainbg_CN.png); mainBg_CN->setPosition(centerPoint); addChild(mainBg_CN); CCSprite* bird = SPRITE(bird.png); bird->setPosition(ccp(VisibleRect::leftTop().x+200,VisibleRect::leftTop().y-150)); CCActionInterval* birdUp = CCMoveBy::create(2,ccp(0,35)); CCActionInterval* birdDown = birdUp->reverse(); CCSequence* birdAction = CCSequence::create(birdUp,birdDown,NULL); bird->runAction(CCRepeatForever::create(birdAction)); mainSceneBatch->addChild(bird); //冒险模式 Boss模式 宠物窝 CCMenuItemSprite* adventureMode = CCMenuItemSprite::create(SPRITE(btn_adventure_normal_CN.png), SPRITE(btn_adventure_pressed_CN.png),SceneManager::shareSceneManager(),menu_selector(SceneManager::toAdventureScene)); CCMenuItemSprite* bossMode = CCMenuItemSprite::create(SPRITE(btn_boss_normal_CN.png), SPRITE(btn_boss_pressed_CN.png)); CCMenuItemSprite* nest = CCMenuItemSprite::create(SPRITE(btn_nest_normal_CN.png), SPRITE(btn_nest_pressed_CN.png)); CCMenu* mainMenu = CCMenu::create(adventureMode,bossMode,nest,NULL); mainMenu->alignItemsHorizontallyWithPadding(20); mainMenu->setPosition(ccp(VisibleRect::center().x,VisibleRect::bottom().y+100)); addChild(mainMenu); //设置和帮助菜单 CCMenuItemSprite* settingBtn = CCMenuItemSprite::create(SPRITE(btn_setting_normal.png),SPRITE(btn_setting_pressed.png), SceneManager::shareSceneManager(),menu_selector(SceneManager::toSettingScene)); CCMenuItemSprite* helpBtn = CCMenuItemSprite::create(SPRITE(btn_help_normal.png),SPRITE(btn_help_pressed.png), SceneManager::shareSceneManager(),menu_selector(SceneManager::toHelpScene)); CCMenu* setMenu = CCMenu::create(settingBtn,helpBtn,NULL); setMenu->alignItemsHorizontallyWithPadding(450); setMenu->setPosition(ccp(VisibleRect::center().x,VisibleRect::center().y-95)); addChild(setMenu); //萝卜叶子的动画 CCActionInterval* shake = CCRotateBy::create(0.1,10); CCActionInterval* shakeBack = shake->reverse(); CCActionInterval* nextDelay = CCDelayTime::create(3); CCActionInterval* repeatDelay = CCDelayTime::create(1); CCCallFunc* callBack = CCCallFunc::create(this,callfunc_selector(GameMain::shakeLeaf)); CCSequence* shakeSeq = CCSequence::create(shake,shakeBack,shake,shakeBack,nextDelay,callBack,repeatDelay,NULL); carrotLeaf2->setTag(kLeaf2); carrotNode->runAction(carrotNodeSeq); carrotLeaf3->runAction(CCRepeatForever::create(shakeSeq)); return true; }
void CMainMenuLayer::drawAnimation() { CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create(MAIN_MENU1_ANI.c_str()); CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache(); cache->addSpriteFramesWithFile(MAIN_MENU1_ANI_PLIST.c_str()); CCArray* animFrames1 = CCArray::createWithCapacity(40); char str[100] = {0}; for(int i = 1; i < 41; i++) { sprintf(str, "manin_menu1_000%02d.png", i); CCSpriteFrame* frame = cache->spriteFrameByName( str ); animFrames1->addObject(frame); } CCSprite*pElement1 = CCSprite::createWithSpriteFrameName("manin_menu1_00001.png"); pElement1->setAnchorPoint(ccp(0,0)); spritebatch->addChild(pElement1); addChild(spritebatch,2); spritebatch->setTag(0); CCAnimation* animation1 = CCAnimation::createWithSpriteFrames(animFrames1,0.05f); CCRepeatForever* repeatAction1 = CCRepeatForever::create(CCAnimate::create(animation1)); pElement1->runAction(repeatAction1); pElement1->setPosition(CCPoint(MAIN_MENU1_IMG_POS)); //menu2 spritebatch = CCSpriteBatchNode::create(MAIN_MENU2_ANI.c_str()); //cache = CCSpriteFrameCache::sharedSpriteFrameCache(); cache->addSpriteFramesWithFile(MAIN_MENU2_ANI_PLIST.c_str()); CCArray* animFrames2 = CCArray::createWithCapacity(4); for(int i = 0; i < 4; i++) { sprintf(str, "main_img2_ani%d.PNG", i); CCSpriteFrame* frame = cache->spriteFrameByName( str ); animFrames2->addObject(frame); } CCSprite*pElement2 = CCSprite::createWithSpriteFrameName("main_img2_ani0.PNG"); pElement2->setAnchorPoint(ccp(0,0)); spritebatch->addChild(pElement2); addChild(spritebatch,4); spritebatch->setTag(0); CCAnimation* animation2 = CCAnimation::createWithSpriteFrames(animFrames2,0.1f); CCRepeatForever* repeatAction2 = CCRepeatForever::create(CCAnimate::create(animation2)); pElement2->runAction(repeatAction2); pElement2->setPosition(CCPoint(MAIN_MENU2_IMG_POS)); //menu3 spritebatch = CCSpriteBatchNode::create(MAIN_MENU3_ANI.c_str()); //cache = CCSpriteFrameCache::sharedSpriteFrameCache(); cache->addSpriteFramesWithFile(MAIN_MENU3_ANI_PLIST.c_str()); CCArray* animFrames3 = CCArray::createWithCapacity(4); for(int i = 0; i < 4; i++) { sprintf(str, "main_img3_ani%d.PNG", i); CCSpriteFrame* frame = cache->spriteFrameByName( str ); animFrames3->addObject(frame); } CCSprite*pElement3 = CCSprite::createWithSpriteFrameName("main_img3_ani0.PNG"); pElement3->setAnchorPoint(ccp(0,0)); spritebatch->addChild(pElement3); addChild(spritebatch,4); spritebatch->setTag(0); CCAnimation* animation3 = CCAnimation::createWithSpriteFrames(animFrames3,0.1f); CCRepeatForever* repeatAction3 = CCRepeatForever::create(CCAnimate::create(animation3)); pElement3->runAction(repeatAction3); pElement3->setPosition(CCPoint(MAIN_MENU3_IMG_POS)); }
bool GameLayer::init(void) { bool bRet = false; do { CC_BREAK_IF(!CCLayer::init()); // 游戏场景背景图 CCSprite *bg = CCSprite::spriteWithFile("Space.png"); CC_BREAK_IF(!bg); bg->setAnchorPoint(CCPointZero); // 为了突出游戏场景中的精灵,将背景色彩变淡 bg->setOpacity(100); this->addChild(bg, 0, 1); // 使用位图字体显示游戏时间 CCLabelBMFont* lbScore = CCLabelBMFont::labelWithString("Time: 0", "font09.fnt"); CC_BREAK_IF(!lbScore); lbScore->setAnchorPoint(ccp(1, 1)); lbScore->setScale(0.6f); this->addChild(lbScore, 1, 3); lbScore->setPosition(ccp(310, 450)); // 载入飞船图像集 CCSpriteBatchNode* mgr = CCSpriteBatchNode::batchNodeWithFile("flight.png", 5); CC_BREAK_IF(!mgr); this->addChild(mgr, 0, 4); // 在状态栏显示一个飞船的图标 CCSprite* sprite = CCSprite::spriteWithTexture(mgr->getTexture(), CCRectMake(0, 0, 31, 30)); CC_BREAK_IF(!sprite); mgr->addChild(sprite, 1, 5); sprite->setScale(1.1f); sprite->setAnchorPoint(ccp(0, 1)); sprite->setPosition(ccp(10, 460)); // 显示当前飞船生命条数 CCLabelBMFont* lbLife = CCLabelBMFont::labelWithString("3", "font09.fnt"); CC_BREAK_IF(!lbLife); lbLife->setAnchorPoint(ccp(0, 1)); lbLife->setScale(0.6f); this->addChild(lbLife, 1, 6); lbLife->setPosition(ccp(50, 450)); // 设定时间回调函数,修改游戏用时显示 this->schedule(schedule_selector(GameLayer::step), 1.0f); // 显示飞船,飞船有不断闪烁的火焰喷射效果 flight = CCSprite::spriteWithTexture(mgr->getTexture(), CCRectMake(0, 0, 31, 30)); CC_BREAK_IF(!flight); flight->setPosition(ccp(160, 30)); flight->setScale(1.6f); mgr->addChild(flight, 1, 99); // 设定动画每一帧的内容 CCAnimation* animation = CCAnimation::animation(); CC_BREAK_IF(!animation); animation->setName("flight"); animation->setDelayPerUnit(0.2f); for (int i = 0; i < 3; ++i) { int x = i % 3; animation->addSpriteFrameWithTexture(mgr->getTexture(), CCRectMake(x*32, 0, 31, 30)); } // 基于动画创建动作 CCAnimate* action = CCAnimate::actionWithAnimation(animation); CC_BREAK_IF(!action); // 主角精灵不断重复动作,实现动态飞行效果 flight->runAction(CCRepeatForever::actionWithAction(action)); // accept touch now this->setTouchEnabled(true); bRet = true; } while (false); return bRet; }
//// merge small piece asprite to a big one CCNode* UIPicture::MergeSmallASprite(CCSprite* sprite) { if (!sprite) return NULL; CCTexture2D* ptexture = RecursiveFindTexture(sprite); if (ptexture == NULL) return sprite; if(sprite->getChildrenCount() == 0) { return sprite; } CCArray* secondTextureSprite = CCArray::create(); while (sprite->getChildrenCount() > 0) { CCTexture2D* ptexture = RecursiveFindTexture(sprite); /// create new batch node which used to store a series of sprites CCSpriteBatchNode * pNode = CCSpriteBatchNode::createWithTexture(ptexture); CCSize size = sprite->getContentSize(); CCPoint pt = sprite->getPosition(); pNode->setContentSize(size); pNode->setAnchorPoint(ccp(0.0, 0.0)); secondTextureSprite->removeAllObjects(); int i = 0; while(sprite->getChildrenCount() > 0) { CCArray* children = sprite->getChildren(); CCSprite* s1 = (CCSprite*)(children->lastObject()); sprite->removeChild(s1, false); if (s1->getTexture() == ptexture) { pNode->addChild(s1, i--); }else { secondTextureSprite->addObject(s1); } } /// copy second texture sprite to sprite CCObject* pTemp; CCARRAY_FOREACH(secondTextureSprite, pTemp) { CCSprite* pPst = (CCSprite*) pTemp; sprite->addChild(pPst); } if (!m_pSpriteNode) { /// 第一次创建时,取第一个sprite位置为当前m_pSpriteNode的位置 m_pSpriteNode = CCNode::create(); m_pSpriteNode->setPosition(pt); m_pSpriteNode->setContentSize(size); m_pSpriteNode->setAnchorPoint(sprite->getAnchorPoint()); pNode->setPosition(CCPointZero); }else { /// convert other sprite to local position CCPoint ptOrgio = m_pSpriteNode->getPosition(); pt = ccpSub(pt , ptOrgio); pNode->setPosition(pt); } m_pSpriteNode->addChild(pNode); }