第三步:移動sprite小精靈
阿新 • • 發佈:2018-11-14
開啟第二步的專案,給遊戲新增敵人enemies
自定義addTarget()函式來完成這項工作
使敵人從螢幕左邊出生,以一個隨機random的速度向左移動
在HelloWorldScene.h標頭檔案加入void addTarget()宣告
在HelloWorldScene.cpp檔案中實現該函式
並新增using namespace cocos2d引入cocos2d名稱空間
1// cpp with cocos2d-x
2void HelloWorld::addTarget()
3{
4 CCSprite *target = CCSprite ::create("Target.png",
5 CCRectMake(0,0,27,40) );
6
7 // 設定敵人出生的Y軸座標
8 CCSize winSize = CCDirector::sharedDirector()->getWinSize();
9 int minY = target->getContentSize().height/2;
10 int maxY = winSize.height
11 - target->getContentSize().height/2;
12 int rangeY = maxY - minY;
13 // srand( TimGetTicks() );
14 int actualY = ( rand() % rangeY ) + minY;
15
16 // Create the target slightly off-screen along the right edge,
17 // and along a random position along the Y axis as calculated
18 target->setPosition(
19 ccp(winSize.width + (target->getContentSize().width/2 ),
20 actualY) );
21 this->addChild(target);
22
23 // 設定隨機速度
24 int minDuration = (int)2.0;
25 int maxDuration = (int)4.0;
26 int rangeDuration = maxDuration - minDuration;
27 // srand( TimGetTicks() );
28 int actualDuration = ( rand() % rangeDuration )
29 + minDuration;
30
31 // 建立移動動作,並設定動作的回撥函式
32 CCFiniteTimeAction* actionMove =
33 CCMoveTo::create( (float)actualDuration,
34 ccp(0 - target->getContentSize().width/2, actualY) );
35 CCFiniteTimeAction* actionMoveDone =
36 CCCallFuncN::create( this,
37 callfuncN_selector(HelloWorld::spriteMoveFinished));
38 target->runAction( CCSequence::create(actionMove,
39 actionMoveDone, NULL) );
40}
宣告和定義HelloWorld::spriteMoveFinished(CCNode* sender)函式
// cpp with cocos2d-x
2void HelloWorld::spriteMoveFinished(CCNode* sender)
3{
4 CCSprite *sprite = (CCSprite *)sender;
5 this->removeChild(sprite, true);
6}
即當敵人從右邊移動到左邊之後,將結束該敵人的生命,不再顯示
現在,敵人已經設計好了,接下來的工作就是把它創建出來
這裡將敵人以每秒一個的速率創建出來
在HelloWord::init()中新增
1// cpp with cocos2d-x
2// Call game logic about every second
3this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 );
並宣告定義HelloWorld::gameLogic(float dt)函式
1// cpp with cocos2d-x
2void HelloWorld::gameLogic(float dt)
3{
4 this->addTarget();
5}
編譯執行一下看看,是不是敵人從右邊出生,移動到左邊之後就消失?