Cocos2d-x制作太空射击游戏
在这篇教程里,我将向你展示如何利用 How to Make a Space Shooter iPhone Game里创建的
制作一个太空游戏。
这里有一个主要的区别——这次是用跨平台的cocs2d-x开发。
这就意味在教程里开发的游戏可以在你的iphone和andorid上运行。当然,再稍微做修改,你可以让它在Windows、Linux或者Mac下运行。
这篇教程基于我们在《COCOS2D-X跨ANDROID&IOS平台开发入门教程PART-1》里所创建的内容。如果你还没有准备好,那么最好先弄懂前面的工程,然后再继续。
深吸一口气,我们就要开始啦!
Getting Started
第一件事情就是下载并解压 space game resources ZIP file。
就像我们在之前教程里面添加两个项目里都可以使用的C++类一样,我们需要以同样的方式来添加这些资源文件使ios和andriod项目都可以引用同样的资源。
我们把这些文件添加到Android工程的Resource目录下面,然后在ios项目里面引用这个目录。
为了方便添加图片和其它资源到我们的工程里,我们需要把它们添加到 $PROJECT_HOME\Resources目录(请记住 $PROJECT_HOME是你Andriod Cocosd-X project-samplecocos2dxandroid的位置)。然而,我们的Eclipse工程只会显示$PROJECT_HOME\android目录下的文件,所以这确实是一个问题!
幸运的是这里有一个简单的变通
:我们在$PROJECT_HOME\Resources 目录下面建立一个符号链接,指向$PROJECT_HOME\android\Resources目录,这样Eclipse就可以看到它们了。
接着,打开终端,在$PROJECT_HOME\android目录下运行如下的命令:
1. ln -s ../Resources ./Resources.
现在拷贝文件到Resources文件夹。请注意,由于跨平台可移植性的原因,你需要避免使用层级式的子目录。尽管子目录在iOS下运行起来很好,但是它们不一定在Android上运行地很好。举例来说,如果你有一个Sprites.pvr.ccz文件在一个SpriteSheet子目录里,在Android里面使用CCSpriteBatchNode::bathNodeWithFile方法将会调用失败并返回一个空指针。
所以,从 space game resources ZIP file里面把单个的文件拷贝到Resource文件夹下去,请记得不要创建任何子目录,仅仅拷贝一个个的文件过来就可以了。在资源文件里存在一个字体的子文件夹,从字体文件夹里把所有的文件拷贝到Resources里时,直接替换就可以了。此外,在压缩文件里有个Classes子文件夹,你不必把它添加到Resources目录下,把它删除就行了。当所有的准备工作完成后就会是下面的样子:
接下来,让我们在iOS工程里引用这些文件,打开你的Xcode工程,创建一个新的Group叫做SharedResources。选择新的Group,在Inspector里点击按钮选择路径,然后把你在Android工程里的资源文件夹选择上。
右键点击SharedResources组,选择添加文件,从Android文件夹里添加所有的文件。目前,你完成所有的项目配置了!
增加一个太空飞船
让我们试试,看是否工作!打开Classes\HelloWorldScene.h,在HelloWorld类开头加入下面代码(在已有public:行的上面)
1. private:
2. cocos2d::CCSpriteBatchNode * _batchNode;
3. cocos2d::CCSprite * _ship;
上面的代码创建了两个私有实例变量 – 一个是sprite batch node,一个是太空飞船精灵
现在切换到HelloWorldScene.cpp,在init方法里,删除从注释“2. add a menu item”到方法最后的所有代码,加入下面代码:
1. _batchNode = CCSpriteBatchNode::batchNodeWithFile("Sprites.pvr.ccz");
2. this->addChild(_batchNode);
3. CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Sprites.plist");
4. _ship = CCSprite::spriteWithSpriteFrameName("SpaceFlier_sm_1.png");
5. CCSize winSize = CCDirector::sharedDirector()->getWinSize();
6. _ship->setPosition(ccp(winSize.width * 0.1, winSize.height * 0.5));
7. _batchNode->addChild(_ship, 1);
8. return true;
注意这些代码与你过去使用的Objective-C版的cocos2d 非常类似。API是有很多相同的地方的,仅仅是有一些与C++的语法不同。
在Android模拟器中编译运行,你应该可以看到你的船出现在屏幕上
最妙的事情是在iOS上也能运行
增加视差滚动
接下来,我们会加入宇宙背景,使它以视差滚动这种很酷的方式来滚动。
首先,我们不得不在所有的类名前面加上cocos2d::这个名字空间,这太烦人了!所以在HelloWorldScene.h类声明前加入下面行:
1. USING_NS_CC ;
接着在HelloWorld的private部分加入一些新的变量(注意我们不再需要加cocos2d前缀):
1. CCParallaxNode *_backgroundNode;
2. CCSprite *_spacedust1;
3. CCSprite *_spacedust2;
4. CCSprite *_planetsunrise;
5. CCSprite *_galaxy;
6. CCSprite *_spacialanomaly;
7. CCSprite *_spacialanomaly2;
然后,在HelloWorldScene.cpp的init方法中,return语句前加入下面代码:
1. // 1) Create the CCParallaxNode
2. _backgroundNode = CCParallaxNode::node() ; //1
3. this->addChild(_backgroundNode,-1) ;
4. // 2) Create the sprites we'll add to the CCParallaxNode
5. _spacedust1 = CCSprite::spriteWithFile("bg_front_spacedust.png");
6. _spacedust2 = CCSprite::spriteWithFile("bg_front_spacedust.png");
7. _planetsunrise = CCSprite::spriteWithFile("bg_planetsunrise.png");
8. _galaxy = CCSprite::spriteWithFile("bg_galaxy.png");
9. _spacialanomaly = CCSprite::spriteWithFile("bg_spacialanomaly.png");
10. _spacialanomaly2 = CCSprite::spriteWithFile("bg_spacialanomaly2.png");
11. // 3) Determine relative movement speeds for space dust and background
12. CCPoint dustSpeed = ccp(0.1, 0.1);
13. CCPoint bgSpeed = ccp(0.05, 0.05);
14. // 4) Add children to CCParallaxNode
15. _backgroundNode->addChild(_spacedust1, 0 , dustSpeed , ccp(0,winSize.height/2) ); // 2
16. _backgroundNode->addChild(_spacedust2, 0 , dustSpeed , ccp( _spacedust1->getContentSize().width,winSize.height/2));
17. _backgroundNode->addChild(_galaxy,-1, bgSpeed , ccp(0,winSize.height * 0.7));
18. _backgroundNode->addChild(_planetsunrise,-1 , bgSpeed,ccp(600,winSize.height * 0));
19. _backgroundNode->addChild(_spacialanomaly,-1, bgSpeed,ccp(900,winSize.height * 0.3));
20. _backgroundNode->addChild(_spacialanomaly2,-1, bgSpeed,ccp(1500,winSize.height * 0.9));
再一次说明,这段代码与我们的《如何使用cocos2d制作一个太空射击游戏》非常类似,只是有些小的句法变化。你可以比较一下2个教程在句法上的不同。
Android模拟器中编译运行,你应该可以看到一个宇宙场景的启动
同样的,也能在iphone上运行
现在使背景滚动,在HelloWorldScene.h中预先声明update方法 – 你可以在private或public部分加入下面代码,但是既然update方法是内部使用的,所以作为一个private方法更恰当:
1. // scheduled Update
2. void update(cocos2d::ccTime dt);
然后在HelloWorldScene.cpp 最后加入下面的方法实现
1. void HelloWorld::update(ccTime dt) {
2. CCPoint backgroundScrollVert = ccp(-1000,0) ;
3. _backgroundNode->setPosition(ccpAdd(_backgroundNode->getPosition(),ccpMult(backgroundScrollVert,dt))) ;
4. }
最后,在init方法末尾(但是在最后的return语句前)调用scheduleUpdate方法
1. this->scheduleUpdate();
编译运行,你将会看到背景滚动!
持续滚动
这时,你应该注意到了背景滚出屏幕后没有循环,那么我们来修这个bug
在我们的 《如何使用cocos2d制作一个太空射击游戏》教程中,我们通过Objective-c的分类(category)扩展了CCParallaxNode类来实现。
不幸的是,C++中是不存在分类的,所以我们需要借助继承来实现之。
我们将去定义一个CCParallaxNode扩展类来扩展
的CCParallaNode。这样做虽然不如Objective-C优雅,但是有时我们需要为软件可移植性做一些牺牲。
在Xcode中,在Glasses group上单击右键,选择New File。选择iOS\C and C++\C++文件末尾,点击Next,为他命名为CCParallaxNodeExtras.cpp,存储到$PROJECT_HOME\Classes,然后点击创建。然后重复上述过程,但要选择iOS\C and C++\Header文件
,来创建CCParallaxNodeExtras.h
用下面的代码替换CCParallaxNodeExtras.h中的内容
1. #ifndef
2. Cocos2DxFirstIosSample_CCParallaxNodeExtras_h #define
3. Cocos2DxFirstIosSample_CCParallaxNodeExtras_h #include “cocos2d.h” USING_NS_CC; class CCParallaxNodeExtras : public CCParallaxNode
4. { public : // Need to provide our own constructor CCParallaxNodeExtras() ; // just to avoid ugly later cast and also for safety
5. static CCParallaxNodeExtras * node() ; // Facility method (we expect to have it soon in COCOS2DX) void incrementOffset(CCPoint
6. offset,CCNode* node) ; } ; #endif
这里我们为CCParallaxNode添加一个新的方法(incrementOffset),我们用它来更新parallax node 每个 child 的位置。当背景移动出屏幕左端的时候我们会使用它来将背景放到屏幕的右端,来实现持续的滚动。 将下面的代码替换到CCParallaxNodeExtras.cpp
1. #include "CCParallaxNodeExtras.h"
2. // Hack to access CCPointObject (which is not a public class)
3. class CCPointObject : CCObject {
4. CC_SYNTHESIZE(CCPoint, m_tRatio, Ratio)
5. CC_SYNTHESIZE(CCPoint, m_tOffset, Offset)
6. CC_SYNTHESIZE(CCNode *,m_pChild, Child) // weak ref
7. };
8. // Need to provide our own constructor
9. CCParallaxNodeExtras::CCParallaxNodeExtras() {
10. CCParallaxNode::CCParallaxNode() ; // call parent constructor
11. }
12. CCParallaxNodeExtras * CCParallaxNodeExtras::node() {
13. return new CCParallaxNodeExtras() ;
14. }
15. void CCParallaxNodeExtras::incrementOffset(CCPoint offset,CCNode* node){
16. for( unsigned int i=0;i < m_pParallaxArray->num;i++) {
17. CCPointObject *point = (CCPointObject *)m_pParallaxArray->arr[i];
18. CCNode * curNode = point->getChild() ;
19. if( curNode->isEqual(node) ) {
20. point->setOffset( ccpAdd(point->getOffset(), offset) );
21. break;
22. }
23. }
24. }
注意,很不幸的是CCPointObject在Cocos2d中并不是公共的类,所以我们需要借住一些小手段来hack。(重定义它为我们的类,并具有相同的签名)。
虽然它能工作的很好,但是他的缺点是,如果CCPointObject改动了,你这里也要跟着改动,否则程序会崩溃。
代码的重点是incrementOffset方法,他和 《如何使用cocos2d制作一个太空射击游戏》中的实现相同,只是用了不同的语言。
下一步,选择HelloWorldScene.h,在文件顶部的#include 语句之后添加这些代码:
1. #include "CCParallaxNodeExtras.h"
然后像下面的代码一样,将private区域中_backgroundNode定义由CCParallaNode改为CCParallaxNodeExtras
1. CCParallaxNodeExtras *_backgroundNode;
然后选择HelloWorldScene.cpp 用下面的代码替换掉section #1(_backgroundNode创建的地方)的第一行。
1. _backgroundNode = CCParallaxNodeExtras::node() ;
最后,添加下面的代码,到update 方法的底部。
1. CCArray *spaceDusts = CCArray::arrayWithCapacity(2) ;
2. spaceDusts->addObject(_spacedust1) ;
3. spaceDusts->addObject(_spacedust2) ;
4. for ( int ii = 0 ; ii count() ; ii++ ) {
5. CCSprite * spaceDust = (CCSprite *)(spaceDusts->objectAtIndex(ii)) ;
6. float xPosition = _backgroundNode->convertToWorldSpace(spaceDust->getPosition()).x ;
7. float size = spaceDust->getContentSize().width ;
8. if ( xPosition < -size ) { _backgroundNode->incrementOffset(ccp(spaceDust->getContentSize().width*2,0),spaceDust) ;
9. }
10. }
11. CCArray *backGrounds = CCArray::arrayWithCapacity(4) ;
12. backGrounds->addObject(_galaxy) ;
13. backGrounds->addObject(_planetsunrise) ;
14. backGrounds->addObject(_spacialanomaly) ;
15. backGrounds->addObject(_spacialanomaly2) ;
16. for ( int ii = 0 ; ii count() ; ii++ ) {
17. CCSprite * background = (CCSprite *)(backGrounds->objectAtIndex(ii)) ;
18. float xPosition = _backgroundNode->convertToWorldSpace(background->getPosition()).x ;
19. float size = background->getContentSize().width ;
20. if ( xPosition < -size ) { _backgroundNode->incrementOffset(ccp(2000,0),background) ;
21. }
22. }
你可以看到,NSArray的替代品是基于STL (C++标准库) 实现的CCArray。我们用可以帮我们自动释放对象的arrayWithCapacity构造函数。注意这里同样也有一个更先进的CCMutableArray来用于存储集合元素。
最后的修改-因为你添加了新文件,你需要把它添加到android工程的Makefile来让他编译正确。于是用Eclipse打开Classes\Android.mk然后改动行LOCAL_SRC_FILES为下面的代码。
1. LOCAL_SRC_FILES := AppDelegate.cpp \
2. HelloWorldScene.cpp \
3. CCParallaxNodeExtras.cpp
编译运行,现在背景可以无限滚动了!
添加星星
添加星星是非常简单的,只是添加下面的代码到HelloWorldScene.cpp的init方法的return之前。
1. HelloWorld::addChild(CCParticleSystemQuad::particleWithFile("Stars1.plist")) ;
2. HelloWorld::addChild(CCParticleSystemQuad::particleWithFile("Stars2.plist")) ;
3. HelloWorld::addChild(CCParticleSystemQuad::particleWithFile("Stars3.plist")) ;
编译运行,漂亮!他已经开始看起来像一个太空游戏了。
使用加速计来移动飞船
在之前的Cocos2D space shooter tutorial里面,我们使用ios的加速计api来检测加速计输入。很明显,ios下面的加速计api是不可以跨平台的,那么我们怎么办呢?
幸运的是,cocos2d-x对加速计进行了封装,我们可以不用关心具体平台api,直接使用抽象后的加速计api就可以了。让我们看看它是怎么工作的吧。
首先,在HelloWorldScnee.H头文件里面添加一个新的私有成员变量:
1. float _shipPointsPerSecY;
然后,添加一个新的public方法声明:
1. virtual void didAccelerate(CCAcceleration* pAccelerationValue);
然后在HelloWorldScene.cpp的init方法的return语句之前添加下列代码:
1. this->setIsAccelerometerEnabled(true);
接下来,在HelloWorldScene.CPP文件底部添加下面这些新方法定义:
1. void HelloWorld::didAccelerate(CCAcceleration* pAccelerationValue) {
2. #define KFILTERINGFACTOR 0.1
3. #define KRESTACCELX -0.6
4. #define KSHIPMAXPOINTSPERSEC (winSize.height*0.5)
5. #define KMAXDIFFX 0.2
6. double rollingX ;
7. // Cocos2DX inverts X and Y accelerometer depending on device orientation
8. // in landscape mode right x=-y and y=x !!! (Strange and confusing choice)
9. pAccelerationValue->x = pAccelerationValue->y ;
10. rollingX = (pAccelerationValue->x * KFILTERINGFACTOR) + (rollingX * (1.0 - KFILTERINGFACTOR));
11. float accelX = pAccelerationValue->x - rollingX ;
12. CCSize winSize = CCDirector::sharedDirector()->getWinSize();
13. float accelDiff = accelX - KRESTACCELX;
14. float accelFraction = accelDiff / KMAXDIFFX;
15. _shipPointsPerSecY = KSHIPMAXPOINTSPERSEC * accelFraction;
16. }
最后,在update方法的底部添加如下代码:
1. CCSize winSize = CCDirector::sharedDirector()->getWinSize();
2. float maxY = winSize.height - _ship->getContentSize().height/2;
3. float minY = _ship->getContentSize().height/2;
4. float diff = (_shipPointsPerSecY * dt) ;
5. float newY = _ship->getPosition().y + diff;
6. newY = MIN(MAX(newY, minY), maxY);
7. _ship->setPosition(ccp(_ship->getPosition().x, newY));
这里的didAccelerate回调函数包含一个CCAcceleration对象,它包含加速计的x、y和z三个方向的数据。我们目前只需要使用x方向的加速计数据就行了,因为我们是沿着设备的x轴进行运动的。
注意: cocos2d-x会根据你的设备是处于portait模式还是landscape模式来切换加速计的x和y方向的值。
如果是Landscape right(也就是我们目前的情况),接收到的x值其实是-y,而y值是x。如果是Landscape left那么接收到的x值是y,而y值是-x。
有点头晕了?呵呵
编译,然后在你的iphone和android设备上测试一下吧,现在你可以倾斜你的设备来移动飞船啦!当然,此时,你不能在模拟器上进行测试,必须使用真机。
添加陨石
是时候给游戏添加一些陨石了!首先在 HelloWorldScene.h里面添加下面一些实例变量:
1. CCMutableArray * _asteroids ;
2. int _nextAsteroid ;
3. float _nextAsteroidSpawn ;
然后,添加一些新的公有方法声明:
1. float randomValueBetween( float low , float high );
2. void setInvisible(CCNode * node);
3. float getTimeTick();
接下来,回到HelloWorldScene.CPP,然后在文件最后添加刚刚的那些辅助方法的实现:
1. float HelloWorld::randomValueBetween( float low , float high ) {
2. return (((float) arc4random() / 0xFFFFFFFFu) * (high - low)) + low;
3. }
4. float HelloWorld::getTimeTick() {
5. timeval time;
6. gettimeofday(&time, NULL);
7. unsigned long millisecs = (time.tv_sec * 1000) + (time.tv_usec / 1000);
8. return (float) millisecs;
9. }
randomValueBetween 是一个可以获得指定范围内的随机浮点数的辅助方法。而 getTimeTick 是一种可移植的方式来得到毫秒级别的时间。
接下来,在init方法的最后创建一个陨石的数组:
1. #define KNUMASTEROIDS 15
2. _asteroids = new CCMutableArray();
3. for(int i = 0; i < KNUMASTEROIDS; ++i) { CCSprite *asteroid = CCSprite::spriteWithSpriteFrameName("asteroid.png");
4. asteroid->setIsVisible(false) ;
5. _batchNode->addChild(asteroid);
6. _asteroids->addObject(asteroid);
7. }
这里,我们使用cocos2d-x的CCMutableArray类来存储ccsprite的数组。注意,我们这里手动调用new操作符,而不是使用arrayWithCapacity来创建对象,这样可以避免使用autorelease机制。
最后,在update方法底部添加下列代码:
1. float curTimeMillis = getTimeTick();
2. if (curTimeMillis > _nextAsteroidSpawn) {
3. float randMillisecs = randomValueBetween(0.20,1.0) * 1000;
4. _nextAsteroidSpawn = randMillisecs + curTimeMillis;
5. float randY = randomValueBetween(0.0,winSize.height);
6. float randDuration = randomValueBetween(2.0,10.0);
7. CCSprite *asteroid = _asteroids->getObjectAtIndex(_nextAsteroid);
8. _nextAsteroid++;
9. if (_nextAsteroid >= _asteroids->count())
10. _nextAsteroid = 0;
11. asteroid->stopAllActions();
12. asteroid->setPosition( ccp(winSize.width+asteroid->getContentSize().width/2, randY));
13. asteroid->setIsVisible(true) ;
14. asteroid->runAction ( CCSequence::actions (
15. CCMoveBy::actionWithDuration(randDuration,ccp(-winSize.width-asteroid->getContentSize().width,0)) ,
16. CCCallFuncN::actionWithTarget(this,callfuncN_selector(HelloWorld::setInvisible)) ,
17. NULL // DO NOT FORGET TO TERMINATE WITH NULL (unexpected in C++)
18. ) ) ;
19. }
再一次说明,这里的代码跟之前的cocos2d代码太像了!注意,这里的callfuncN_selector调用跟objc里面的selector机制太像了!
注意:由于CCSequence::actions方法的参数列
采用的是变长参数,你其实可以忽略掉最后一个NULL参数,因为对于c++来讲,这个参数没有意义。
但是,考虑到兼容性的原因,因为cocos2d-x开发者想保持跟cocos2d的高度一致,所以,这里需要一个NULL终止符。如果你在你的代码里面不提供的话,那么你的程序将会崩溃。
最后一步就是添加setInvisible回调函数的实现:
1. void HelloWorld::setInvisible(CCNode * node) {
2. node->setIsVisible(false) ;
3. }
编译并运行,有陨石!下面是iphone3GS的运行效果截图:
下面是Android Samsung Galaxy S的运行效果截图:
发射激光
是时候让我们的飞船发射激光了!在HelloWorldScene.h里面添加下列私有成员变量:
1. CCMutableArray * _shipLasers ;
2. int _nextShipLaser ;
现在,添加一个新的公有方法声明:
1. virtual void ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
然后,在HelloWorldScene.cpp的init方法的return语句之前添加下列代码:
1. #define KNUMLASERS 5
2. _shipLasers = new CCMutableArray();
3. for(int i = 0; i < KNUMLASERS; ++i) { CCSprite *shipLaser = CCSprite::spriteWithSpriteFrameName("laserbeam_blue.png");
4. shipLaser->setIsVisible(false) ;
5. _batchNode->addChild(shipLaser);
6. _shipLasers->addObject(shipLaser);
7. }
8. this->setIsTouchEnabled(true) ;
最后,在文件的底部实现ccTouchesBegan方法;
1. void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event)
2. {
3. CCSize winSize = CCDirector::sharedDirector()->getWinSize() ;
4. CCSprite *shipLaser = _shipLasers->getObjectAtIndex(_nextShipLaser++);
5. if ( _nextShipLaser >= _shipLasers->count() )
6. _nextShipLaser = 0;
7. shipLaser->setPosition( ccpAdd( _ship->getPosition(), ccp(shipLaser->getContentSize().width/2, 0)));
8. shipLaser->setIsVisible(true) ;
9. shipLaser->stopAllActions() ;
10. shipLaser->runAction( CCSequence::actions (
11. CCMoveBy::actionWithDuration(0.5,ccp(winSize.width, 0)),
12. CCCallFuncN::actionWithTarget(this,callfuncN_selector(HelloWorld::setInvisible)) ,
13. NULL // DO NOT FORGET TO TERMINATE WITH NULL
14. ) ) ;
15. }
编译并运行,现在你可以发射激光了!下面是iphone 3GS下面的运行截图:
下面是Android Samsung Galaxy S的运行截图:
简单的碰撞检测
接下来,我们想添加一些代码来检测激光和小行星间的碰撞,以及当小行星被撞击时爆炸。完成这项功能的代码和《如何使用cocos2d制作一个太空射击游戏》中的相当相似,但是用到了一些新的语法。
注意,我们会介绍C++迭代器来处理CCMutableArray。首先,在HelloWorldScene.h添加一个新的私有变量:
1. int _lives ;
接着,在HelloWorldScene.h的update函数的底部添加如下代码:
1. // Asteroids
2. CCMutableArray::CCMutableArrayIterator itAster , itLaser ;
3. for ( itAster = _asteroids->begin() ; itAster != _asteroids->end() ; itAster++ ) {
4. CCSprite *asteroid = (CCSprite *)*itAster;
5. if ( ! asteroid->getIsVisible() )
6. continue ;
7. for ( itLaser = _shipLasers->begin() ; itLaser != _shipLasers->end() ; itLaser++ ) {
8. CCSprite *shipLaser = (CCSprite *)*itLaser;
9. if ( ! shipLaser->getIsVisible() )
10. continue ;
11. if ( CCRect::CCRectIntersectsRect(shipLaser->boundingBox(), asteroid->boundingBox()) ) {
12. shipLaser->setIsVisible(false) ;
13. asteroid->setIsVisible(false) ;
14. continue ;
15. }
16. }
17. if ( CCRect::CCRectIntersectsRect(_ship->boundingBox(), asteroid->boundingBox()) ) {
18. asteroid->setIsVisible(false) ;
19. _ship->runAction( CCBlink::actionWithDuration(1.0, 9)) ;
20. _lives-- ;
21. }
22. }
编译并运行,现在你可以使小行星爆炸了!当然,你会发现当激光碰撞到小行星,他们并没有爆炸就消失了。这是因为我们没有为爆炸添加粒子效果。之前我们已经将星星添加到了粒子系统中,根据最初的教程,把爆炸加入粒子系统将是相当简单的任务。把这个当成额外的课外作业吧!
胜利/失败检测
将胜利或失败的检测代码转换到Cocos2D-X也是直截了当的。
切换回HelloWorldScene.h并在类的声明前添加一个枚举变量:
1. typedef enum {
2. KENDREASONWIN,
3. KENDREASONLOSE
4. } EndReason;
现在在HelloWorld类添加两个私有变量:
1. double _gameOverTime ;
2. bool _gameOver ;
接下来,添加两个私有方法的声明;
1. void endScene( EndReason endReason ) ;
2. void restartTapped() ;
接着,切换到HelloWorldScene.cpp并在init函数的return前添加如下代码:
1. _lives = 3 ;
2. double curTime = getTimeTick() ;
3. _gameOverTime = curTime + 30000 ;
在update的结尾,添加如下代码:
1. if ( _lives stopAllActions() ;
2. _ship->setIsVisible(false) ;
3. this->endScene(KENDREASONLOSE) ;
4. } else if ( curTimeMillis >= _gameOverTime ) {
5. this->endScene(KENDREASONWIN) ;
6. }
最后,在文件的结尾添加新方法的实现:
1. void HelloWorld::restartTapped() {
2. CCDirector::sharedDirector()->replaceScene
3. ( CCTransitionZoomFlipX::transitionWithDuration(0.5, this->scene()));
4. // reschedule
5. this->scheduleUpdate() ;
6. }
7. void HelloWorld::endScene( EndReason endReason ) {
8. if ( _gameOver )
9. return ;
10. _gameOver = true ;
11. CCSize winSize = CCDirector::sharedDirector()->getWinSize() ;
12. char message[10] = "You Win" ;
13. if ( endReason == KENDREASONLOSE )
14. strcpy(message,"You Lose") ;
15. CCLabelBMFont * label ;
16. label = CCLabelBMFont::labelWithString(message ,"Arial.fnt" );
17. label->setScale(0.1) ;
18. label->setPosition( ccp( winSize.width/2 , winSize.height*0.6)) ;
19. this->addChild(label) ;
20. CCLabelBMFont * restartLabel ;
21. restartLabel = CCLabelBMFont::labelWithString("Restart" ,"Arial.fnt" );
22. CCMenuItemLabel *restartItem = CCMenuItemLabel::itemWithLabel(restartLabel, this, menu_selector(HelloWorld::restartTapped) );
23. restartItem->setScale(0.1) ;
24. restartItem->setPosition( ccp( winSize.width/2 , winSize.height*0.4)) ;
25. CCMenu *menu = CCMenu::menuWithItems(restartItem, NULL);
26. menu->setPosition(CCPointZero);
27. this->addChild(menu) ;
28. // clear label and menu
29. restartItem->runAction( CCScaleTo::actionWithDuration(0.5, 1.0)) ;
30. label ->runAction( CCScaleTo::actionWithDuration(0.5, 1.0)) ;
31. // Terminate update callback
32. this->unscheduleUpdate() ;
33. }
注意最初的代码版本和Cocos2D-X代码版本的一个区别是我们不得不在游戏开始和结束时定时或取消定时对update的回调。
编译并运行,如果你的船撞击太多次就会死!
免费的音乐和音效
安卓不支持CAF格式的声音文件,所以我们要做的第一件事就是把原始声音文件替换为一种可在安卓上使用的格式。
打开终端,输入如下命令(不要忘记在第一个命令中用安卓项目的真实路径替换$PROJECT_HOME,否则命令将无法运行):
1. cd $PROJECT_HOME/Resourc