cocos2dx一仿微信飞机大战游戏实战二

仿微信飞机大战游戏实战二,游戏代码的编写,直接上代码

HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

class HelloWorld : public cocos2d::CCLayer
{
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone

	HelloWorld();
	~HelloWorld();

    virtual bool init();  

    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();
    
    // a selector callback
    void menuCloseCallback(CCObject* pSender);

	void initData();  

	//开始动画
	cocos2d::CCSprite *sprite;
	void startAnim();

	void startGame(CCObject* test);  

	//飘落的雪花
	void pSnow();
    
    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);

	
};

#endif // __HELLOWORLD_SCENE_H__


HelloWorldScene.cpp

#include "HelloWorldScene.h"
#include "GameScene.h"

USING_NS_CC;

HelloWorld::HelloWorld(){}
HelloWorld::~HelloWorld(){}

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }

	CCSize size=CCDirector::sharedDirector()->getWinSize();
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

    /
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(HelloWorld::menuCloseCallback));
    
	pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
                                origin.y + pCloseItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition(CCPointZero);
    this->addChild(pMenu, 1);

    /
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    
	CCLabelTTF* pLabel = CCLabelTTF::create("Play Plane", "Arial", 80);
    
    // position the label on the center of the screen
    pLabel->setPosition(ccp(size.width/2,size.height/4*3+80));

    // add the label as a child to this layer
    this->addChild(pLabel, 1);

	CCActionInterval * test=CCJumpBy::create(2,ccp(0,0),10,5);
	//pLabel->runAction(CCRepeatForever::create(CCSequence::create(test,NULL)));
	pLabel->runAction( CCRepeatForever::create(test));
	

    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("ui/bg.png");

    // position the sprite on the center of the screen
    pSprite->setPosition(ccp(size.width/2 + origin.x, size.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);


	CCMenuItemFont *startItem=CCMenuItemFont::create("start", this,menu_selector   (HelloWorld::startGame));  
	startItem->setPosition(ccp(size.width/2, size.height/2+200));  
	startItem->setFontSizeObj(55);  
	startItem->setFontNameObj("Georgia-Bold");  
	CCMenu *pMenu2 = CCMenu::create(startItem, NULL);  
	pMenu2->setPosition(CCPointZero);  
	this->addChild(pMenu2, 1);  
    
	CCActionInterval *sc=CCScaleBy::create(1.0f,1.5f);
	CCActionInterval *b=CCEaseBounceInOut::create(sc);
	startItem->runAction(CCRepeatForever::create(CCSequence::create(b,b->reverse(),NULL)));

	this->startAnim();

	this->initData();

	/*CCActionInterval *actionw=CCWaves3D::create(5,40,CCPointMake(20.0f,10.0f),10.0f);*/

	this->pSnow();

    return true;
}

//加载图片资源
void HelloWorld::initData()  
{  


	//CCSpriteFrameCache *frameCache1=CCSpriteFrameCache::sharedSpriteFrameCache();  

	//frameCache1->addSpriteFramesWithFile("ui/shoot.plist"); 

	CCSpriteFrameCache *frameCache=CCSpriteFrameCache::sharedSpriteFrameCache();  

	frameCache->addSpriteFramesWithFile("ui/shoot.plist"); 

}  

void HelloWorld::startAnim(){

	CCSpriteFrameCache *frame=CCSpriteFrameCache::sharedSpriteFrameCache();  

	frame->addSpriteFramesWithFile("ui/shoot_background.plist");
	
	CCSize size=CCDirector::sharedDirector()->getWinSize();
	sprite=CCSprite::createWithSpriteFrameName("game_loading1.png");
	sprite->setPosition(ccp(size.width/2, size.height/2+100));
	this->addChild(sprite,1);

	CCArray *array=CCArray::create();

	for (int i=1; i<5; i++)
	{

		CCString *string=CCString::createWithFormat("game_loading%i.png",i);
		CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(string->getCString());

		array->addObject(frame);

	}

	CCAnimation *animation=CCAnimation::createWithSpriteFrames(array,0.5);
	CCAnimate *animate=CCAnimate::create(animation);
	CCRepeatForever *ac1=CCRepeatForever::create(animate);
	sprite->runAction(ac1);
}

//开始游戏  
void HelloWorld::startGame(CCObject* test)
{  
	sprite->stopAllActions();

	CCScene *scene=CCScene::create();  

	GameScene *layer=GameScene::create();  

	scene->addChild(layer);  

	//CCDirector::sharedDirector()->replaceScene(scene);  
	CCDirector::sharedDirector()->replaceScene(CCTransitionShrinkGrow::create(1,scene));  
	 
}  

void HelloWorld::pSnow(){

	CCParticleSystem *pa=CCParticleSnow::create();
	pa->setSpeed(125);
	pa->setSpeedVar(125);
	pa->setRadialAccel(10);
	pa->setRadialAccelVar(5);
	pa->setBlendAdditive(true);
	pa->setGravity(ccp(0,-10));
	pa->setAutoRemoveOnFinish(true);
	pa->retain();
	this->addChild(pa,3);
}

void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
	CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
    CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
#endif
}


敌机精灵类

EnemyPlane.h

#ifndef __ENEMYPLANE_H__
#define __ENEMYPLANE_H__

#include <iostream>
#include "cocos2d.h"
#include "cocos-ext.h"

USING_NS_CC;
using namespace cocos2d;
using namespace cocos2d::extension;

class EnemyPlane:public cocos2d::CCSprite{
public:

	EnemyPlane();
	~EnemyPlane();

	//飞机的种类
	int planeType;

	//飞机的血量
	int hp;

	//飞机的速度
	int speed;

	//加载敌机精灵
	 static EnemyPlane* createWithSpriteFrameName(const char *spriteFrameName);  

};

#endif __ENEMYPLANE_H__


EnemyPlane.cpp

#include "EnemyPlane.h"


//加载敌机


EnemyPlane::EnemyPlane(){}

EnemyPlane::~EnemyPlane(){}

//加载敌机精灵
EnemyPlane* EnemyPlane::createWithSpriteFrameName(const char *spriteFrameName){

	EnemyPlane *pSprite=new EnemyPlane;

	if(pSprite && pSprite->initWithSpriteFrameName(spriteFrameName)){

		pSprite->autorelease();

		return pSprite;

	}

	CC_SAFE_DELETE(pSprite);

	return NULL;
}


物品精灵类

Bonus.h

#ifndef __CHANGEBULLET_H__
#define __CHANGEBULLET_H__

#include <iostream>
#include "cocos2d.h"
#include "cocos-ext.h"

USING_NS_CC;
using namespace cocos2d;
using namespace cocos2d::extension;

typedef enum prosType
{
	propsTypeBomb = 1,  //炸弹
    propsTypeBullet = 2  //blue子弹

};

class Bonus:public cocos2d::CCNode{

public:

	Bonus();
	~Bonus();

	cocos2d::CCSprite *prop;  

	//UFO的类型
	prosType bulletType;  

	void initWithType(prosType type);  

	//UFO出现的动画
	void propAnimation();  

	//改变子弹
	static Bonus* create(void);  

	CC_SYNTHESIZE_RETAIN(cocos2d::CCSprite*, _prop, Prop);  
};

#endif __CHANGEBULLET_H__

Bonus.cpp
Bonus.cpp

#include "Bonus.h"


//换子弹

Bonus::Bonus(){};

Bonus::~Bonus(){};

Bonus* Bonus::create(){
	
	Bonus *pb=new Bonus();

	if(pb && pb->init()){
		pb->autorelease();
	}else
	{
		CC_SAFE_DELETE(pb);
	}

	return pb;
}

//UFO的类型
void Bonus::initWithType(prosType type){

	bulletType=type;

	CCString *string=CCString::createWithFormat("ufo%d.png",type);  
	prop=CCSprite::createWithSpriteFrameName(string->getCString());  
	prop->setPosition(ccp((rand()%200 + 10)*2,400*2));  
}

//物品出现动画  
void Bonus::propAnimation(){

	CCMoveTo *ac1=CCMoveTo::create(1, ccp(prop->getPosition().x, 250*2));  
	CCMoveTo *ac2=CCMoveTo::create(0.4, ccp(prop->getPosition().x, 252*2));  
	CCMoveTo *ac3=CCMoveTo::create(1, ccp(prop->getPosition().x, 632*2));  
	CCMoveTo *ac4=CCMoveTo::create(2, ccp(prop->getPosition().x, -55*2));  

	prop->runAction(CCSequence::create(ac1,ac2,ac3,ac4,NULL)); 
}

游戏逻辑的实现

GameScene.h

#ifndef __GAMESCENE_SCENE_H__
#define __GAMESCENE_SCENE_H__

#include <iostream>
#include "cocos2d.h"
#include "SimpleAudioEngine.h" 
#include "cocos-ext.h"
#include "EnemyPlane.h"
#include "Bonus.h"
#include <string.h>

USING_NS_CC;
using namespace cocos2d;
using namespace cocos2d::extension;
using namespace CocosDenshion;
using namespace std;

class GameScene : public cocos2d::CCLayer
{

public:

	GameScene();
	~GameScene();

	virtual bool init();
	//static cocos2d::CCScene* scene();
	
	 CREATE_FUNC(GameScene);

	 cocos2d::CCSize size;

	//加载UI
	void initUI();

	//加载初始化的数据
	void initData();

	//背景滚动
	void scrollBg();

	//更新的函数,飞机和子弹的移动
	void update(float t);

	//背景图
	cocos2d::CCSprite *bgSprite1; 
	cocos2d::CCSprite *bgSprite2;


	int bgHeight; //图片的高度
	int bg_speed; //图片高度滚动的速度

	//玩家的飞机精灵
	cocos2d::CCSprite *playSprite;

	//触摸函数,移动玩家的飞机
	virtual void ccTouchesMoved(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEven); 

	cocos2d::CCPoint planePos(cocos2d::CCPoint newPos);

	//子弹
	cocos2d::CCSprite *bullet;

	//子弹的速度
	int bulletSpeed;

	//制造子弹
	void madeBullet();

	//重置子弹
	void resetBullet();

	//开火
	void firingBullets();

	//玩家飞机爆炸动画  
	void playerAnimation();


	//敌机
	int smallPlaneTime;  
	int mediumPlaneTime;  
	int bigPlaneTime;  

	//保存敌机精灵的CCArray数组
	cocos2d::CCArray* planeArray;
	

	//添加敌机
	void addEnemyPlane();

	//小飞机
	int smaPlanSpeed;
	EnemyPlane* makeSmallPlane();

	//中等飞机
	int medPlanSpeed;
	EnemyPlane* makeMediumPlane();

	//大型飞机
	int bigPlaneSpeed;
	EnemyPlane* makeBigPlane();

	//移动飞机
	void moveEnemyPlane(); 


	//碰撞
	void collisionDetection();  

	//飞机碰撞的动画
	void enemyAnimation(EnemyPlane *enemyPlane);  

	//敌机被击打时的动画
	void hitAnimation(EnemyPlane *enemyPlane);  


	void AnimationEnd(CCNode *object);   

	//得分  
	int scoreInt;  

	//分数
	cocos2d::CCLabelTTF* scoreLabel;



	//换物品种类
	void addBulletTypeTip();

	//空降物品时间计数
	int propTime;

	Bonus *prop;

	bool isVisible;
	bool isBigBullet;
	bool isChangeBullet;

	//子弹持续时间
	int bulletlastTime;

	void bulletLastTime();

	//游戏结束
	//游戏结束的标志
	bool isGameOver;

	void gameOver();

	//游戏暂停  
	cocos2d::CCMenu *pause_menu;
	void gamePause(CCObject* pSender);

	//游戏重玩
	void gameRestart(CCObject* pSender);
    cocos2d::CCMenu *start_menu;

	//暂停再开始
	void gameStart(CCObject* pSender);


	cocos2d::CCLayerColor *gameoverLayer;

	//预先加载音乐文件
	void preMusic();

	//背景音乐
	void bgSound();

	//开火的声音
	void playFireSound();

	//小飞机爆炸声
	void smallPlaneDownSound();

	//中等飞机爆炸声
	void mediumPlaneDownSound();

	//大型飞机爆炸声
	void bigPlaneDownSound();

	//获取奖励声
	void getBonusSound();

	//出现奖励声
	void presentBonusSound();

	//使用奖励声
	void useBonusSound();

	//保存分数(最高分)
	void saveScore();
};

#endif __GAMESCENE_SCENE_H__

GameScene.cpp

#include "GameScene.h"


GameScene::GameScene(){
	//planeArray=CCArray::create(); //在构造函数中创建CCArray
	//CC_SAFE_RETAIN(planeArray);
}
GameScene::~GameScene(){
	//CC_SAFE_RELEASE_NULL(planeArray); //释放掉CCArray
}

bool GameScene::init()
{
	
	if ( !CCLayer::init() )
	{
		return false;
	}
	this->preMusic();

	this->initData();

	this->initUI();

	isVisible = false;

	//制造发射子弹
	this->madeBullet();
	this->resetBullet();

	//系统的刷新
	this->scheduleUpdate();

	return true;

}

void GameScene::initData()
{

	//背景音乐
	this->bgSound();

	planeArray = CCArray ::create();
	planeArray->retain();
	 
	//背景图片的高度
	bgHeight=800;

	bg_speed=2;

	//敌机三种不同类型的初始速度
	smaPlanSpeed=20;
	medPlanSpeed=8;
	bigPlaneSpeed=5;
	
	//添加触摸
	this->setTouchEnabled(true);

	//CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this, 0);

	//planeArray=CCArray::create();

	//创建分数LanelTTF
	size=CCDirector::sharedDirector()->getWinSize();
	scoreLabel=CCLabelTTF::create("0", "MarkerFelt-Thin", 44);  
	scoreLabel->setPosition(ccp(10,size.height-50));  
	scoreLabel->setColor(ccc3(0, 0, 0));  
	scoreLabel->setAnchorPoint(ccp(0, 0));  
	this->addChild(scoreLabel,3);

	//暂停按钮

	start_menu=NULL;

	CCMenuItemImage *pause=CCMenuItemImage::create("game_pause_nor.png","game_pause_pressed.png",this,menu_selector(GameScene::gamePause));
	pause->setPosition(ccp(size.width-50,size.height-20));

	pause_menu=CCMenu::create(pause,NULL);
	pause_menu->setPosition(CCPointZero);
	this->addChild(pause_menu,1);

	//初始化敌机类型出现的参数
	this->smallPlaneTime=0;
	this->mediumPlaneTime=0;
	this->bigPlaneTime=0;		

	//子弹的初速度 25
	bulletSpeed = 25;
	bulletlastTime = 1200;

	//空降物品计数
	propTime = 0;

	//得分
	scoreInt = 0;

	isBigBullet = false;
	isChangeBullet = false;

	isGameOver = false;

}


void GameScene::initUI()
{

	//背景图
	bgSprite1=CCSprite::create("ui/bg_game.png");
	
	
	bgSprite1->setAnchorPoint(ccp(0.5, 0));
	bgSprite1->setPosition(ccp(240, 0));

	this->addChild(bgSprite1, 0);


	bgSprite2=CCSprite::create("ui/bg_game.png");
	bgSprite2->setAnchorPoint(ccp(0.5, 0));
	bgSprite2->setPosition(ccp(240, bgHeight-1));

	this->addChild(bgSprite2, 0);

	//玩家
	playSprite=CCSprite::createWithSpriteFrameName("hero1.png");
	playSprite->setPosition(ccp(240, 200));

	this->addChild(playSprite, 3);


	//自身动画
	CCArray *array=CCArray::create();

	for (int i=1; i<3; i++)
	{

		CCString *string=CCString::createWithFormat("hero%d.png",i);
		CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(string->getCString());

		array->addObject(frame);

	}
	
	CCAnimation *animation=CCAnimation::createWithSpriteFrames(array,0.1);
	CCAnimate *animate=CCAnimate::create(animation);

	CCRepeatForever *ac1=CCRepeatForever::create(animate);

	playSprite->runAction(ac1);

}

//循环滚动背景
void GameScene::scrollBg()
{

	bgHeight=bgHeight-bg_speed;

	if (bgHeight<=0)
	{
		bgHeight=800;
	}

	bgSprite1->setPosition(ccp(bgSprite1->getPosition().x, bgHeight-800));
	bgSprite2->setPosition(ccp(bgSprite2->getPosition().x, bgHeight-1));

}


//刷新
void GameScene::update(float t)
{

	if (false == isGameOver)
	{

		//背景滚动
		this->scrollBg();

		//玩家飞机发射子弹
		this->firingBullets();

		//添加敌机
		this->addEnemyPlane();

		//移动敌机
		this->moveEnemyPlane();

		//碰撞检测
		this->collisionDetection();

		//添加物品
		this->addBulletTypeTip();  

		//子弹持续时间
		this->bulletLastTime();  

	}

}

//手指移动飞机  
	void GameScene::ccTouchesMoved(CCSet *pTouches,CCEvent *pEven)  
{  

	if(!CCDirector::sharedDirector()->isPaused())  
	{  
	CCSetIterator it = pTouches->begin();  

	CCTouch* touch = (CCTouch*)(* it);  


	CCPoint curLocation = CCDirector::sharedDirector()->convertToGL(touch->getLocationInView());  

	CCRect planeRect=this->playSprite->boundingBox(); 
	planeRect.origin.x-=45;  
	planeRect.origin.y-=45;  
	planeRect.size.width+=45;  
	planeRect.size.height+=45; 

	if (planeRect.containsPoint(curLocation)) //判断触摸点是否是玩家飞机的精灵上?
	{

	//前一个点的坐标  
	CCPoint oldLocation=touch->getPreviousLocation();  

	CCPoint translation=ccpSub(curLocation, oldLocation);  


	//CCLOG("%f",translation.y);  

	//相减,得到偏移量  
	playSprite->setPosition(this->planePos(translation));  
	
	}
	}
}  


CCPoint GameScene::planePos(CCPoint newPos)  
{  
	
	CCPoint point=newPos;  

	point.x=playSprite->getPosition().x+newPos.x;  
	point.y=playSprite->getPosition().y+newPos.y;  

	//CCSize size=CCDirector::sharedDirector()->getWinSize();

	//边界x轴判断
	if (point.x>=size.width) {  
		point.x = size.width;  
	}else if (point.x <= 15) {  
		point.x = 15;  
	} 

	//CCLOG("ps<<",playSprite->getContentSize());

	if (point.y >=size.height-50*2) {  
		point.y = size.height-50*2;  
	}else if (point.y <= 43*2) {  
		point.y = 43*2;  
	}  
	
	return point;  

}  

//制造子弹
void GameScene::madeBullet(){

	//嘿嘿,加载子弹精灵的小技巧(普通的子弹和大子弹)
	bullet=CCSprite ::createWithSpriteFrameName((!isBigBullet)?"bullet1.png":"bullet2.png");

	this->addChild(bullet,3);

	this->playFireSound();
	
}

//重置子弹
void GameScene::resetBullet(){

	//CCSize size=CCDirector::sharedDirector()->getWinSize();

	//这里判断是否是发射大子弹
	  if ((isBigBullet && isChangeBullet) || (!isBigBullet && isChangeBullet))
    {
		CCLog("------------>%d",isBigBullet);
        bullet->removeFromParentAndCleanup(false);
        this->madeBullet();
        isChangeBullet = false;
    }

	bulletSpeed = (size.height - (playSprite->getPosition().y + 50))/15;  

	if (bulletSpeed<5)  
	{  
		bulletSpeed=5;  
	}  
	
	bullet->setPosition(ccp(playSprite->getPosition().x, playSprite->getPosition().y+50));  
}

//发射子弹
void GameScene::firingBullets(){

	//CCSize size=CCDirector::sharedDirector()->getWinSize();

	//不断改变子弹的Y坐标
	bullet->setPosition(ccp(bullet->getPosition().x, bullet->getPosition().y+bulletSpeed));  

	//检测子弹是否超出了屏幕的高度,如果是则重新设置子弹的位置
	if (bullet->getPosition().y > size.height)  
	{  
		this->resetBullet();  
		this->playFireSound();
	}  
	
}

//添加敌机
void GameScene::addEnemyPlane(){

	smallPlaneTime++;  
	mediumPlaneTime ++;  
	bigPlaneTime ++;  

	//控制发射敌机的时间(小飞机1秒,中等飞机5秒,大型飞机10秒)
	if (smallPlaneTime > 30)  
	{  
		EnemyPlane *smallPlane=this->makeSmallPlane();  

		this->addChild(smallPlane, 3);  

		planeArray->addObject(smallPlane);  

		smallPlaneTime = 0;  
	}  

	if (mediumPlaneTime > 240)  
	{  

		EnemyPlane *mediumPlane=this->makeMediumPlane();  

		this->addChild(mediumPlane, 3);  

		planeArray->addObject(mediumPlane);  

		mediumPlaneTime = 0;  

	}  

	if (bigPlaneTime > 480)  
	{  

		EnemyPlane *bigPlane=this->makeBigPlane();  

		this->addChild(bigPlane, 3);  

		planeArray->addObject(bigPlane);  

		bigPlaneTime = 0;  

	}  
}

//制造小飞机
EnemyPlane* GameScene::makeSmallPlane(){

  //rand()%240 表示的意思是一个随机回去240中的一个整数

	EnemyPlane *smallPlane=EnemyPlane::createWithSpriteFrameName("enemy1.png");
	smallPlane->setPosition(ccp(rand()%240+20,800));

	smallPlane->planeType=1;
	smallPlane->hp=1;
	smallPlane->speed=rand()%smaPlanSpeed+2;

	return smallPlane;
}

//制造中等飞机
EnemyPlane* GameScene::makeMediumPlane(){

	EnemyPlane *mediumPlane=EnemyPlane::createWithSpriteFrameName("enemy2.png");
	mediumPlane->setPosition(ccp(rand()%240+20,800));

	mediumPlane->planeType=2;
	mediumPlane->hp=15;
	mediumPlane->speed=rand()%medPlanSpeed+2;

	return mediumPlane;
}

//制造大飞机
EnemyPlane* GameScene::makeBigPlane(){

//大飞机精灵
EnemyPlane *bigPlane=EnemyPlane::createWithSpriteFrameName("enemy3_n1.png");
bigPlane->setPosition(ccp(rand()%240+50,1200));

bigPlane->planeType=3;
bigPlane->hp=25;
bigPlane->speed=rand()%bigPlaneSpeed+2;

return bigPlane;
	
}

//移动敌机的精灵
void GameScene::moveEnemyPlane(){
	for (int i=0;i<planeArray->count();i++)  
	{  
		EnemyPlane *tmpPlane=(EnemyPlane *)planeArray->objectAtIndex(i);  

		tmpPlane->setPosition(ccp(tmpPlane->getPosition().x,tmpPlane->getPosition().y - tmpPlane->speed));  

		//判断是否是超出屏幕的底部了,如果是则从CCArray中删除
		if (tmpPlane->getPosition().y<(-75*2))  
		{  

			planeArray->removeObject(tmpPlane);  

			//tmpPlane->removeFromParentAndCleanup(false);  

		}  

	}  
}

//碰撞检测
void GameScene::collisionDetection(){

	//子弹所在的矩形区域
	CCRect bulltRect=bullet->boundingBox();

	//敌机数组
	for(int i=0;i<planeArray->count();i++){

		EnemyPlane* enemyPlane=(EnemyPlane*)planeArray->objectAtIndex(i);

		//子弹矩形和敌机矩形
		if (bulltRect.intersectsRect(enemyPlane->boundingBox()))
		{
			//子弹打到碰到飞机了,子弹要消失,重置子弹
			this->resetBullet();


			//敌机的血量减少(普通的子弹减1,大子弹减2)

			if (true==isBigBullet )
			{
				CCLog("------------------->%d",enemyPlane->hp);
				enemyPlane->hp=enemyPlane->hp-2;

			}else
			{
				enemyPlane->hp=enemyPlane->hp-1;
			}
			
			
			//敌机的血量为0时播放敌机飞机爆炸动画
			if(enemyPlane->hp <= 0){
				this->enemyAnimation(enemyPlane);
				planeArray->removeObject(enemyPlane);
			}else //击打时播放击打时的动画
			{
				this->hitAnimation(enemyPlane);
			}
		}
	}

	//飞机和空降物,判断是否换子弹
	if (isVisible==true)
	{
		CCRect playRect=playSprite->boundingBox();
		CCRect propRect=prop->prop->boundingBox();

		if (playRect.intersectsRect(propRect))
		{

			prop->prop->stopAllActions();
			prop->prop->removeFromParentAndCleanup(true);

			isVisible=false;

			this->getBonusSound();

			//换子弹
			if (prop->bulletType==propsTypeBullet)
			{
				isBigBullet = true;
				isChangeBullet = true;
				/*this->madeBullet();*/
			}
			//炸弹
			else
			{
				for (int i=0; i<planeArray->count(); i++)
				{
					EnemyPlane *enemyPlane=(EnemyPlane *)planeArray->objectAtIndex(i);
					//爆炸动画
					this->enemyAnimation(enemyPlane);
				}

				this->useBonusSound();
				planeArray->removeAllObjects();

			}

		}

	}


	//敌机和玩家的飞机是否发生碰撞

	//获取玩家飞机精灵所在的的矩形框
	CCRect playRec=playSprite->boundingBox();
	
	//只是把玩家飞机的那个空白区域缩减
	playRec.origin.x += 15*2;
	playRec.size.width -= 25*2;
	playRec.origin.y -= 10*2;
	playRec.size.height -= 10*2;

	for (int i=0; i<planeArray->count(); i++)
	{

		EnemyPlane *enemyPlane=(EnemyPlane *)planeArray->objectAtIndex(i);

		if (playRec.intersectsRect(enemyPlane->boundingBox()))
		{
			
			this->playerAnimation();
			this->enemyAnimation(enemyPlane);

			planeArray->removeObject(enemyPlane);

			//planeArray->removeAllObjects();

			//CCDelayTime::create(5.0f);
			//this->gameOver();

			/*CCSequence *s=CCSequence::create(CCDelayTime::create(5.0f),CCCallFunc::create(this, callfunc_selector(GameScene::gameOver)));  

			this->runAction(s);*/
			CCFiniteTimeAction *action = CCSequence::create(  
				CCDelayTime::create(0.5f),  
				CCCallFunc::create(this,callfunc_selector(GameScene::gameOver)),  
				NULL  
				);  

			this->runAction(action);

		}
	}


}


//玩家飞机爆炸动画
void GameScene::playerAnimation()
{
	playSprite->stopAllActions();

	CCArray *array=CCArray::create();

	for (int i=1; i<4; i++)
	{

		CCString *string=CCString::createWithFormat("hero_blowup_n%i.png",i);
		CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(string->getCString());

		array->addObject(frame);

	}

	CCAnimation *animation=CCAnimation::createWithSpriteFrames(array,0.1);
	CCAnimate *animate=CCAnimate::create(animation);

	CCRepeatForever *ac1=CCRepeatForever::create(animate);

	playSprite->runAction(ac1);

	array->removeAllObjects();
}




//敌人飞机爆炸动画
void GameScene::enemyAnimation(EnemyPlane *enemyPlane){

	int animationNum = 0;  

	//小飞机爆炸
	if (enemyPlane->planeType == 1)
	{	
		animationNum = 5;  
		scoreInt += 1000;
	}

	//中等飞机爆炸
	if (enemyPlane->planeType == 2)
	{
		animationNum = 5;  
		scoreInt += 2000;
	}

	//大型飞机爆炸
	if (enemyPlane->planeType == 3)
	{
		animationNum = 7;  
		scoreInt += 10000;

	}

	//设置分数
	CCString *string=CCString::createWithFormat("%i",scoreInt);
	scoreLabel->setString(string->getCString());
	
	//设置背景图片滚动的图片
	//if (scoreInt >= 100000)
	//{
	//	bg_speed=scoreInt%100000;
	//}

	//关卡设置(调整敌机的速度与背景滚动的速度)
	if (scoreInt >= 20000 && smaPlanSpeed!=25)
	{
		smaPlanSpeed=25;
		medPlanSpeed=15;
		bigPlaneSpeed=10;

		bg_speed=5;

	}else if (scoreInt >= 100000 && smaPlanSpeed!=30)
	{
		smaPlanSpeed=30;
		medPlanSpeed=20;
		bigPlaneSpeed=15;

		bg_speed=10;

	}else if(scoreInt >= 500000 && smaPlanSpeed!=45)
	{
		smaPlanSpeed=45;
		medPlanSpeed=30;
		bigPlaneSpeed=25;

		bg_speed=15;

	}else if (scoreInt >= 1000000 && smaPlanSpeed!=80)
	{
		smaPlanSpeed=80;
		medPlanSpeed=45;
		bigPlaneSpeed=35;

		bg_speed=25;
	}
	
	//停止动画
	enemyPlane->stopAllActions();
	
	//动画效果  
	CCArray *array=CCArray::create();  

	for (int i=1; i<animationNum; i++)  
	{  

		CCString *string=CCString::createWithFormat("enemy%i_down%i.png",enemyPlane->planeType,i);  
		CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(string->getCString());  

		array->addObject(frame);  

	}  

	CCAnimation *animation=CCAnimation::createWithSpriteFrames(array,0.1);  
	CCAnimate *animate=CCAnimate::create(animation);  


	CCSequence *seq=CCSequence::create(animate,CCCallFuncN::create(this, callfuncN_selector(GameScene::AnimationEnd)),NULL);  

	enemyPlane->runAction(seq);  

	array->removeAllObjects();  

	if (enemyPlane->planeType == 1)  
	{  
		//  SimpleAudioEngine::sharedEngine()->playEffect("music/enemy1_down.mp3");  
		this->smallPlaneDownSound();
	}  
	else if (enemyPlane->planeType == 2)  
	{  
		//   SimpleAudioEngine::sharedEngine()->playEffect("music/enemy2_down.mp3");  
		this->mediumPlaneDownSound();
	}  
	else if (enemyPlane->planeType == 3)  
	{  
		//    SimpleAudioEngine::sharedEngine()->playEffect("enemy3_down.mp3");  
		this->bigPlaneDownSound();
	}  

}

void GameScene::hitAnimation(EnemyPlane *enemyPlane){
	//中等飞机
	if(enemyPlane->planeType == 2){
		if (enemyPlane->hp == 13)
		{

			CCArray *array=CCArray::create();
			for (int i=1;i<5;i++)
			{
				CCString *string=CCString::createWithFormat("enemy2_down%i.png",i);
				CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(string->getCString());
				array->addObject(frame);

			}

			CCAnimation *animation=CCAnimation::createWithSpriteFrames(array,0.1);  
			CCAnimate *animate=CCAnimate::create(animation);  

			CCRepeatForever *ac1=CCRepeatForever::create(animate);  

			enemyPlane->runAction(ac1);  

			array->removeAllObjects();  

		}
	}

	if (enemyPlane->planeType == 3)
	{
		if (enemyPlane->hp == 20)
		{
			CCArray *array=CCArray::create();
			for (int i=1;i<7;i++)
			{
				CCString *string=CCString::createWithFormat("enemy3_down%i.png",i);
				CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(string->getCString());
				array->addObject(frame);

			}

			CCAnimation *animation=CCAnimation::createWithSpriteFrames(array,0.1);  
			CCAnimate *animate=CCAnimate::create(animation);  

			CCRepeatForever *ac1=CCRepeatForever::create(animate);  

			enemyPlane->runAction(ac1);  

			array->removeAllObjects();  
		}
	}
}

//动画结束
void GameScene::AnimationEnd(CCNode *object){

	EnemyPlane *enemyPlane=(EnemyPlane *)object;  

	enemyPlane->removeFromParentAndCleanup(false);  
}

//空降物品
void GameScene::addBulletTypeTip()
{

	propTime++;

	if (propTime>500)
	{

		prop=Bonus::create();

		prop->initWithType((prosType)(rand()%2 + 1));

		/*CCLOG("<<<<<<<<<<<<<prop",prop+(rand()%240 + 23));*/

		this->addChild(prop->prop);

		prop->propAnimation();

		prop->retain();

		propTime=0;

		isVisible=true;

		this->presentBonusSound();

	}
}


//对于换子弹的时间控制
void GameScene::bulletLastTime()
{

	if (isBigBullet)
	{
		if (bulletlastTime > 0)
		{
			bulletlastTime --;
		}
		else
		{
			bulletlastTime = 1200;
			isBigBullet = false;
			isChangeBullet = true;
		}
	}
}



//游戏结束
void GameScene::gameOver()
{

	isGameOver=true;
	
	//this->stopAllActions();
	this->gamePause(NULL);

	//CCSize size=CCDirector::sharedDirector()->getWinSize();

	gameoverLayer=CCLayerColor::create(ccc4(215, 221, 222, 255), size.width, size.height);
	gameoverLayer->setPosition(ccp(0, 0));
	this->addChild(gameoverLayer, 3);

	//保存最高分数
	this->saveScore();

	CCLabelTTF *ttfLabel=CCLabelTTF::create("Cur_Score", "MarkerFelt-Thin", 50);
	ttfLabel->setPosition(ccp(gameoverLayer->getContentSize().width/2-ttfLabel->getContentSize().width/2, gameoverLayer->getContentSize().height/2+50));
	ttfLabel->setColor(ccc3(0, 0, 0));
	ttfLabel->setAnchorPoint(ccp(0, 0));
	gameoverLayer->addChild(ttfLabel, 1);



	CCLabelTTF *scLabel=CCLabelTTF::create(scoreLabel->getString(), "MarkerFelt-Thin", 55);
	scLabel->setPosition(ccp(gameoverLayer->getContentSize().width/2-scLabel->getContentSize().width/2, gameoverLayer->getContentSize().height/2-10));
	scLabel->setColor(ccc3(0, 0, 0));
	scLabel->setAnchorPoint(ccp(0, 0));
	gameoverLayer->addChild(scLabel, 1);


	CCMenuItemFont *startItem=CCMenuItemFont::create("RePlay", this,menu_selector(GameScene::gameRestart));  
	startItem->setPosition(ccp(gameoverLayer->getContentSize().width/2, size.height/2-100));  
	startItem->setFontSizeObj(50);  
	startItem->setFontNameObj("Georgia-Bold");  
	startItem->setColor(ccc3(0, 0, 0));  
	CCMenu *pMenu = CCMenu::create(startItem, NULL);  
	pMenu->setPosition(CCPointZero);  
	gameoverLayer->addChild(pMenu, 1);  

	CCActionInterval *sc=CCScaleBy::create(1.0f,1.5f);
	CCActionInterval *b=CCEaseBounceInOut::create(sc);
	startItem->runAction(CCRepeatForever::create(CCSequence::create(b,b->reverse(),NULL)));
}

//游戏暂停  
void GameScene::gamePause(CCObject* pSender)  
{  
	 


	if (isGameOver==false)  
	{  
		//暂停没有?

		if(!CCDirector::sharedDirector()->isPaused()){
			CCDirector::sharedDirector()->pause(); 
		}

		pause_menu->setVisible(false);

		if (NULL != start_menu)
		{
			start_menu->setVisible(true);
		}else
		{
			//CCSize size=CCDirector::sharedDirector()->getWinSize();
			CCMenuItemImage *start=CCMenuItemImage::create("game_resume_nor.png","game_resume_pressed.png",this,menu_selector(GameScene::gameStart));
			start->setPosition(ccp(size.width-50,size.height-20));

			start_menu=CCMenu::create(start,NULL);
			start_menu->setPosition(CCPointZero);
			this->addChild(start_menu,1);
		}
		
	
		
		isGameOver=true;
	}  
	else  
	{  
		CCObject *object;  

		CCARRAY_FOREACH(this->getChildren(), object)  
		{  

			CCNode *node=(CCNode *)object;  

			node->stopAllActions();

		}  
	}  

}

//重玩
void GameScene::gameRestart(CCObject* pSender){
	
	//移除CCLayerColor
	this->removeChild(gameoverLayer,true);

	//清除屏幕上的节点
	//this->removeAllChildrenWithCleanup(true);
	//this->removeFromParentAndCleanup(false);
	this->removeAllChildren();
	

	this->initData();
	this->initUI();

	isGameOver=false;
	isVisible = false;

	//制造发射子弹
	this->madeBullet();
	this->resetBullet();
}

void GameScene::gameStart(CCObject* pSender){
	if (true == isGameOver)
	{
		CCDirector::sharedDirector()->resume(); 
		//CCDirector::sharedDirector()->popScene();
		start_menu->setVisible(false);
		pause_menu->setVisible(true);
		isGameOver = false;

	}
}


//游戏中的声音

void GameScene::preMusic(){ //加载游戏中音乐资源

	//备注 win32不支持MP3格式的
#if(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

#define MUSIC_BG "music/game_music.wav"
#define MUSIC_BULLET "music/bullet.wav"
#define MUSIC_ENEMY1 "music/enemy1_down.wav"
#define MUSIC_ENEMY2 "music/enemy2_down.wav"
#define MUSIC_ENEMY3 "music/enemy3_down.wav"
#define MUSIC_BOMB "music/get_bomb.wav"
#define MUSIC_PREBOMB "music/out_porp.wav"
#define MUSIC_USEBOMB "music/use_bomb.wav"

#elif(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

#define MUSIC_BG "music/game_music.mp3"
#define MUSIC_BULLET "music/bullet.mp3"
#define MUSIC_ENEMY1 "music/enemy1_down.mp3"
#define MUSIC_ENEMY2 "music/enemy2_down.mp3"
#define MUSIC_ENEMY3 "music/enemy3_down.mp3"
#define MUSIC_BOMB "music/get_bomb.mp3"
#define MUSIC_PREBOMB "music/out_porp.mp3"
#define MUSIC_USEBOMB "music/use_bomb.mp3"

#endif

	CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_BG);

	CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_BULLET);

	CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_ENEMY1);

	CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_ENEMY2);

	CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_ENEMY3);

	CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_BOMB);
	CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_PREBOMB);
	CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_USEBOMB);

}
void GameScene::bgSound()
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(MUSIC_BG,true);
}
void GameScene::playFireSound()
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(MUSIC_BULLET);
}
void GameScene::smallPlaneDownSound()
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(MUSIC_ENEMY1);
}
void GameScene::mediumPlaneDownSound()
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(MUSIC_ENEMY2);
}
void GameScene::bigPlaneDownSound()
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(MUSIC_ENEMY3);
}
void GameScene::getBonusSound(){
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(MUSIC_BOMB);
}
void GameScene::presentBonusSound(){
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(MUSIC_PREBOMB);
}
void GameScene::useBonusSound(){
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(MUSIC_USEBOMB);
}

void GameScene::saveScore(){
	if (CCUserDefault::sharedUserDefault()->getBoolForKey("isScore",false))
	{
		string score=CCUserDefault::sharedUserDefault()->getStringForKey("score","");
		CCLog("----score----%s",score.c_str());

		CCLabelTTF* lastScore=CCLabelTTF::create(score.c_str(), "MarkerFelt-Thin", 44);
		lastScore->setPosition(ccp(size.width/2,size.height/4*3));
		lastScore->setColor(ccc3(0,0,0));
		gameoverLayer->addChild(lastScore);

		CCUserDefault::sharedUserDefault()->setStringForKey("score",scoreLabel->getString());
		CCUserDefault::sharedUserDefault()->flush();

		CCLog("---------%s",scoreLabel->getString());

	}else
	{
		CCUserDefault::sharedUserDefault()->setBoolForKey("isScore",true);
		CCUserDefault::sharedUserDefault()->setStringForKey("score",scoreLabel->getString());

		CCUserDefault::sharedUserDefault()->flush();		
	}
}



完工了,可以运行看看效果啦




源码下载




  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值