加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2d-x学习之飞镖打妖怪

发布时间:2020-12-14 14:17:46 所属栏目:百科 来源:网络整理
导读:cocos2d-x引擎版本是2.2.0 这篇博客其实不是给给人看的,只是给我自己看的,以便自己熟悉里面的代码 总共四个文件: #ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"class HelloWorld : public cocos2d::CCLayerColor{pu


cocos2d-x引擎版本是2.2.0

这篇博客其实不是给给人看的,只是给我自己看的,以便自己熟悉里面的代码

总共四个文件:

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

class HelloWorld : public cocos2d::CCLayerColor
{
public:
	~ HelloWorld();

    // Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone
    virtual bool init();  

    // there's no 'id' in cpp,so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();

	//小孩对象
	cocos2d::CCSprite *player;

	//怪物对象
	cocos2d::CCSprite *target;

	//怪物集合
	cocos2d::CCArray *_targets;

	//飞镖集合
	cocos2d::CCArray *_projs;

	//击中次数
	int _ShotTimes;

    // a selector callback
    void menuCloseCallback(CCObject* pSender);

	//按钮的响应
	void responseFunc(CCObject* obj);
    
    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);
	void myDefine(CCNode *who);
	void CreateTarget();
	void gameLogic(float dt);
	void ccTouchesEnded(cocos2d::CCSet *pTouches,cocos2d::CCEvent *pEvent);
	void update(float delta);
};

#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "GameOverLayer.h"

USING_NS_CC;

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;
}

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
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayerColor::initWithColor(ccc4(0,255,255)) )
    {
        return false;
    }
    
//     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("Hello World","Arial",24);
//     
//     // position the label on the center of the screen
//     pLabel->setPosition(ccp(origin.x + visibleSize.width/2,//                             origin.y + visibleSize.height - pLabel->getContentSize().height));
// 
//     // add the label as a child to this layer
//     this->addChild(pLabel,1);
// 
//     // add "HelloWorld" splash screen"
//     CCSprite* pSprite = CCSprite::create("HelloWorld.png");
// 
//     // position the sprite on the center of the screen
//     pSprite->setPosition(ccp(visibleSize.width/2 + origin.x,visibleSize.height/2 + origin.y));
// 
//     // add the sprite as a child to this layer
//     this->addChild(pSprite,0);

	//屏幕大小
	CCSize screenSize = CCDirector::sharedDirector()->getVisibleSize();

	//添加小孩
	player = CCSprite::create("Player.png");
	player->setPosition(ccp(0+20,screenSize.height/2));
	this->addChild(player);

// 	//菜单的使用
// 	CCMenuItemImage* item = CCMenuItemImage::create("button2.png",// 		"button2.png",// 		this,// 		menu_selector(HelloWorld::responseFunc));
// 	item->setPosition(ccp(30,30));
// 	CCMenu *menu = CCMenu::create(item,NULL);
// 	this->addChild(menu);
// 
// 	target = CCSprite::create("Target.png");
// 	target->setPosition(ccp(screenSize.width -2,40));
// 	this->addChild(target);

	//定时生成怪物
	this->schedule(schedule_selector(HelloWorld::gameLogic),1);

	//检测碰撞
	this->schedule(schedule_selector(HelloWorld::update));

	//允许触屏
	this->setTouchEnabled(true);

	_targets = new cocos2d::CCArray;
	_projs = new cocos2d::CCArray;

	//播放背景音乐
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("background-music-aac.wav",true);

	//成员初始化
	_ShotTimes = 0;

    return true;
}

//屏幕触摸---发射飞镖
void HelloWorld::ccTouchesEnded(CCSet *pTouches,CCEvent *pEvent)
{
	//获得屏幕大小
	CCSize screenSize = CCDirector::sharedDirector()->getVisibleSize();

	//获得触摸点
	CCTouch * touch = (CCTouch *)pTouches->anyObject();
	CCPoint locInView = touch->getLocationInView();
	CCPoint loc = CCDirector::sharedDirector()->convertToGL(locInView);
	if (loc.x <= 20)
	{
		return;
	}

	//加载飞镖
	CCSprite *proj = CCSprite::create("Projectile.png");
	proj->setPosition(ccp(20,screenSize.height/2.0));
	this->addChild(proj);

	//播放飞镖音乐
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("pew-pew-lei.wav");

	//加入到飞镖数组
	_projs->addObject(proj);
	proj->setTag(2);

	double dx = loc.x -20;
	double dy = loc.y -screenSize.height / 2.0;
	double d = sqrt(dx * dx + dy * dy);

	//发射长度
	double D = sqrt(screenSize.width * screenSize.width + screenSize.height * screenSize.height);

	double ratio = D / d;
	double endx = ratio * dx +20;
	double endy = ratio * dy + screenSize.height / 2.0;

	CCMoveTo *move = CCMoveTo::create(D / 320,ccp(endx,endy));
	CCCallFuncN * moveFinish = CCCallFuncN::create(this,callfuncN_selector(HelloWorld::myDefine));
	CCSequence *actions = CCSequence::create(move,moveFinish,NULL);
	proj->runAction(actions);
}

//定时器回调函数
void HelloWorld::gameLogic(float dt)
{
	CreateTarget();
}

//创建会运行的怪物
void HelloWorld::CreateTarget()
{
	//获取屏幕宽度
	CCSize screenSize = CCDirector::sharedDirector()->getVisibleSize();

	int y = rand() % (int)(screenSize.height);

	//怪物精灵
	CCSprite *target = CCSprite::create("Target.png");
	target->setPosition(ccp(screenSize.width -2,y));
	this->addChild(target);

	//加入到怪物数组
	_targets->addObject(target);
	target->setTag(1);

	CCMoveTo *move = CCMoveTo::create(3,ccp(0,y));
	CCCallFuncN *disapear = CCCallFuncN::create(this,disapear,NULL);

	target->runAction(actions);
}

//按钮响应
void HelloWorld::responseFunc(CCObject* obj)
{
	//CCLOG("button is pressed");
	CCMoveTo *move = CCMoveTo::create(3,40));
	CCCallFuncN *disapear = CCCallFuncN::create(this,NULL);

	target->runAction(actions);
}

//让怪物和飞镖消失
void HelloWorld::myDefine(CCNode *who)
{
	who->removeFromParentAndCleanup(true);

	//销毁精灵
	int tag = who->getTag();
	if (tag == 1)//怪物消失
	{
		_targets->removeObject(who);

		//切换到游戏结束场景
		CCScene *gameOverScene = GameOverLayer::scene();
		GameOverLayer *layer = (GameOverLayer*)gameOverScene->getChildByTag(100);
		layer->_lable->setString("Sorry,You Failed~!");
		CCDirector::sharedDirector()->replaceScene(gameOverScene);

	}
	else if (tag == 2)//飞镖消失
	{
		_projs->removeObject(who);
	}
}

//析构函数
HelloWorld::~HelloWorld()
{
	if (_projs != NULL)
	{
		_projs->release();
	}
	if (_targets != NULL)
	{
		_targets->release();
	}
}

//不停地检测碰撞事件
void HelloWorld::update(float delta)
{
	//准备删除的临时集合
	CCArray *toDelTarget = new CCArray;
	CCArray *toDelProj = new CCArray;

	CCObject *itarget,*iproj;
	//遍历所有怪物
	CCARRAY_FOREACH(_targets,itarget)
	{
		CCSprite * target = (CCSprite*)itarget;
		CCRect targetZone = CCRectMake(target->getPositionX(),target->getPositionY(),target->getContentSize().width,target->getContentSize().height);
		//遍历所有飞镖
		CCARRAY_FOREACH(_projs,iproj)
		{
			CCSprite * proj = (CCSprite*)iproj;
			CCRect projZone = CCRectMake(proj->getPositionX(),proj->getPositionY(),proj->getContentSize().width,proj->getContentSize().height);

			//检查重合
			if (projZone.intersectsRect(targetZone))
			{
				toDelTarget->addObject(target);
				toDelProj->addObject(proj);

				//检测游戏结束
				if (++_ShotTimes == 5)
				{
					//切换到游戏结束场景
					CCScene *gameOverScene = GameOverLayer::scene();
					GameOverLayer *layer = (GameOverLayer*)gameOverScene->getChildByTag(100);
					layer->_lable->setString("Congratulations,You Succeed~!");
					CCDirector::sharedDirector()->replaceScene(gameOverScene);
				}
			}
		}
	}

	//删除碰撞精灵
	CCARRAY_FOREACH(toDelProj,iproj)
	{
		_projs->removeObject(iproj);
		CCSprite * proj = (CCSprite*)iproj;
		proj->removeFromParentAndCleanup(true);
	}
	CCARRAY_FOREACH(toDelTarget,itarget)
	{
		_targets->removeObject(itarget);
		CCSprite * target = (CCSprite*)itarget;
		target->removeFromParentAndCleanup(true);
	}
}

#pragma once
#include "cocos2d.h"
class GameOverLayer : public cocos2d::CCLayerColor
{
public:
	GameOverLayer(void);
	~GameOverLayer(void);

public:
	bool init();
	CREATE_FUNC(GameOverLayer);
	static cocos2d::CCScene* scene();
	void ReturnToGame(cocos2d::CCNode *node);
public:
	cocos2d::CCLabelTTF * _lable;
};

#include "GameOverLayer.h"
#include "HelloWorldScene.h"

USING_NS_CC;

GameOverLayer::GameOverLayer(void)
{
}


GameOverLayer::~GameOverLayer(void)
{
	if (_lable)
	{
		_lable->release();
	}
}

bool GameOverLayer::init()
{
	if (CCLayerColor::initWithColor(ccc4(0,255)))
	{
		_lable = CCLabelTTF::create("word","Artial",40);
		CCSize size = CCDirector::sharedDirector()->getVisibleSize();
		_lable->setPosition(ccp(size.width/2,size.height/2));
		this->addChild(_lable);

		_lable->retain();

		//再次切换到游戏
		CCDelayTime *delay = CCDelayTime::create(5);
		CCCallFuncN * returnToGame = CCCallFuncN::create(this,callfuncN_selector(GameOverLayer::ReturnToGame));
		this->runAction(CCSequence::create(delay,returnToGame,NULL));

		return true;
	}
	return false;
}

//切换回游戏
void GameOverLayer::ReturnToGame(CCNode *node)
{
	CCDirector::sharedDirector()->replaceScene(HelloWorld::scene());
}

//创建场景
cocos2d::CCScene* GameOverLayer::scene()
{
	CCScene * scene = CCScene::create();
	GameOverLayer *layer = GameOverLayer::create();
	layer->setTag(100);

	scene->addChild(layer);
	return scene;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读