打开第二步的项目,给游戏添加敌人enemies
自定义addTarget()函数来完成这项工作
使敌人从屏幕左边出生,以一个随机random的速度向左移动
在HelloWorldScene.h头文件加入void addTarget()声明
在HelloWorldScene.cpp文件中实现该函数
并添加using namespace cocos2d引入cocos2d命名空间
1
2void HelloWorld::addTarget()
3{
4 CCSprite *target = CCSprite::create("Target.png",
5 CCRectMake(0,0,27,40) );
6
7
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
14 int actualY = ( rand() % rangeY ) + minY;
15
16
17
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
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)函数
2void HelloWorld::spriteMoveFinished(CCNode* sender)
3{
4 CCSprite *sprite = (CCSprite *)sender;
5 this->removeChild(sprite, true);
6}
即当敌人从右边移动到左边之后,将结束该敌人的生命,不再显示
现在,敌人已经设计好了,接下来的工作就是把它创建出来
这里将敌人以每秒一个的速率创建出来
在HelloWord::init()中添加
1
2
3this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 );
并声明定义HelloWorld::gameLogic(float dt)函数
1
2void HelloWorld::gameLogic(float dt)
3{
4 this->addTarget();
5}
编译运行一下看看,是不是敌人从右边出生,移动到左边之后就消失?