笨木头 Little Runner

笨木头 Little Runner,第1张

概述1. 写笔记主要是为了同强大的忘性作斗争,学习《Cocos2d-x 3.x游戏开发之旅》所记。 2. 以下参照书本,跑出来的效果图,所以主要还是把代码贴上来,方便日后查询。 3.下面开始贴代码 创建基类,为人物和金币所继承.Entity 继承与Node. #ifndef _ENTITY_H_#define _ENTITY_H_#include"cocos2d.h"USING_NS_CC;

1. 写笔记主要是为了同强大的忘性作斗争,学习《Cocos2d-x 3.x游戏开发之旅》所记。

2. 以下参照书本,跑出来的效果图,所以主要还是把代码贴上来,方便日后查询。



3.下面开始贴代码

创建基类,为人物和金币所继承.Entity 继承与Node.

#ifndef _ENTITY_H_#define _ENTITY_H_#include"cocos2d.h"USING_NS_CC;class Entity : public Node{public:	Entity();	~Entity();	Sprite* getSprite();	voID bindSprite(Sprite* sprite);private:	Sprite* m_sprite;};#endif#include"Entity.h"#include"Player.h"Entity::Entity(){	m_sprite = NulL;}Entity::~Entity(){}Sprite* Entity::getSprite(){	return this->m_sprite;}voID Entity::bindSprite(Sprite* sprite){	this->m_sprite = sprite;	this->addChild(m_sprite);        /*由于需要做碰撞检测,而Node的默认宽高属性(0,0),所以需要获取精灵的宽高,设置给Entity.这样Entity就有了Sprite对象的宽高。*/	Size size = m_sprite->getContentSize();	m_sprite->setposition(Point(size.wIDth*0.5f,size.height*0.5f));	this->setContentSize(size);}

2.创建主角类Player和金币类Monster.
#ifndef _PLAYER_H_#define _PLAYER_H_#include"cocos2d.h"#include"Entity.h"using namespace cocos2d;#define JUMP_ACTION_TAG 1class Player : public Entity{public:	Player();	~Player();	CREATE_FUNC(Player);	virtual bool init();	voID jump();	voID hit();	int getiHP();	voID resetData();private:	bool b_isJumPing;	int m_iHP;};#endif#include"Player.h"//#include"FlowWord.h"Player::Player(){	b_isJumPing = false;	m_iHP = 1000;}Player::~Player(){}bool Player::init(){	return true;}voID Player::hit()//碰撞时,人物的动作{	if(getSprite() == NulL)	{		return;	}	m_iHP -= 15;	if(m_iHP < 0)	{		m_iHP = 0;	}	//FlowWord* flowWord = FlowWord::create();	//this->addChild(flowWord);	//flowWord->showWord("-15",GetSpoolfileHandle);	auto backMove = MoveBy::create(0.1f,Point(-20,0));	auto forwardMove = MoveBy::create(0.1f,Point(20,0));	auto backRotate = RotateBy::create(0.1f,-5,0);	auto forwardRotate = RotateBy::create(0.1f,5,0);	auto backAction = Spawn::create(backMove,backRotate,NulL);	auto forwardAction = Spawn::create(forwardMove,forwardRotate,NulL);	auto actions = Sequence::create(backAction,forwardAction,NulL);	stopAllActions();	resetData();	runAction(actions);}voID Player::resetData(){	if(b_isJumPing)	{		b_isJumPing = false;	}	setposition(Point(200,140));	setScale(1.0f);	setRotation(0);}int Player::getiHP(){	return m_iHP;}voID Player::jump(){	if(getSprite() == NulL)		return;	if(b_isJumPing)		return;	b_isJumPing = true;	auto jump = JumpBy::create(2.0f,Point(0,0),250,1);//原地跳跃,高度250像素,跳跃一次	auto callFunc = CallFunc::create([&]()	{		b_isJumPing = false;	});	auto jumpAction = Sequence::create(jump,callFunc,NulL);	this->runAction(jumpAction);}<pre name="code" >#ifndef _MONSTER_H_#define _MONSTER_H_#include"Entity.h"#include"Player.h"class Monster:public Entity{public:	Monster();	~Monster();	CREATE_FUNC(Monster);	virtual bool init();public:	voID show();	voID hIDe();	voID reset();	bool isAlive();	bool isCollIDeWithPlayer(Player* player);private:	bool b_isAlive;};#endif#include"Monster.h"Monster::Monster(){	b_isAlive = false;}Monster::~Monster(){}bool Monster::init(){	return true;}voID Monster::show(){	if(getSprite() != NulL)	{		setVisible(true);		b_isAlive = true;	}}voID Monster::hIDe(){	if(getSprite() != NulL)	{		setVisible(false);		reset();		b_isAlive = false;	}}voID Monster::reset(){	if(getSprite() != NulL)	{		setposition(Point(800+CCRANDOM_0_1() * 2000,200-CCRANDOM_0_1()*100));	}}bool Monster::isAlive(){ 	return b_isAlive;}bool Monster::isCollIDeWithPlayer(Player* player){	if(player == NulL || getSprite() == NulL)		return false;	Rect entityRect = player->getBoundingBox();//获取碰撞检测对象的boundingBox	Point monsterPos = getposition();	return entityRect.containsPoint(monsterPos);}

3.金币管理类,负责金币的创建,管理。

#ifndef _MANAGERMONSTER_H_#define _MANAGERMONSTER_H_#include "cocos2d.h"#include "Monster.h"USING_NS_CC;#define MAX_MONSTER_NUM 10class MonsterManager:public Node{public:	CREATE_FUNC(MonsterManager);	virtual bool init();	virtual voID update(float dt);private :	voID createMonster();public:	voID bindplayer(Player* player);private: 	Vector<Monster*> m_monsterarr;//Vector容器的应用	Player* m_player;};#endif#include"MonsterManager.h"#include"Player.h"#include"Monster.h"bool MonsterManager::init(){	createMonster();	this->scheduleUpdate();	return true;}voID MonsterManager::createMonster(){	Monster* monster = NulL;	Sprite* sprite = NulL;	for(int i = 0; i < MAX_MONSTER_NUM; i++)	{		monster = Monster::create();		monster->bindSprite(Sprite::create("monster.png"));		monster->reset();		this->addChild(monster);		m_monsterarr.pushBack(monster);	}} voID MonsterManager::update(float dt) {	 for(auto monster:m_monsterarr)	 {		 if(monster == NulL)			 continue;		 if(monster->isAlive())		 {			 monster->setpositionX(monster->getpositionX() - 4);			 if(monster->getpositionX() < 0)			 {				 monster->hIDe();			 }		 }		 else		 {			 monster->show();		 }		if(monster->getpositionX() < 0)		{			monster->hIDe();		}		else if(monster->isCollIDeWithPlayer(m_player))		{			m_player->hit();			monster->hIDe();		}	 } } voID MonsterManager::bindplayer(Player* player) {	m_player = player; }

4.创建场景类
#ifndef _TolLGATESCENE_H_#define _TolLGATESCENE_H_#include "cocos2d.h"using namespace cocos2d;#include"editor-support/cocostudio/CCSGUIReader.h"#include"ui/CocosGUI.h"using namespace cocos2d::ui;using namespace cocostudio; class Player;class TollgateScene : public Layer{public:	static Scene* createScene();    virtual bool init();	CREATE_FUNC(TollgateScene);	virtual voID update(float delta);//update函数的调用private:	voID initBG();	voID loadUI();	voID jumpEvent(Ref*,touchEventType type);private:	Sprite* m_bg1;	Sprite* m_bg2;	Player* m_player;	int m_iscore;	Text* m_scoreLab;	Loadingbar* m_hpbar;};#endif#include"TollgateScene.h"#include"Player.h"#include"Entity.h"#include"cocos2d.h"#include"MonsterManager.h"Scene* TollgateScene::createScene(){    // 'scene' is an autorelease object    auto scene = Scene::create();        // 'layer' is an autorelease object    auto layer = TollgateScene::create();    // add layer as a child to scene    scene->addChild(layer);    // return the scene    return scene;}bool TollgateScene::init(){	if(!Layer::init())	{		return false;	}        //尽量不要使用多线程,Cocos2d-x的Node对象提供了一个update函数,在游戏的每一帧都会调用update函数,我们只要调用它便可以	this->scheduleUpdate();//这句表示我们开启调用update函数的功能	Size visibleSize = Director::getInstance()->getVisibleSize();	Sprite* TitleSprite = Sprite::create("Title.png");	TitleSprite->setposition(Point(visibleSize.wIDth/2,visibleSize.height-50));	this->addChild(TitleSprite,2);	m_player = Player::create();	m_player->bindSprite(Sprite::create("sprite.png"));	m_player->setposition(Point(200,visibleSize.height / 4));	this->addChild(m_player,3);	initBG();	MonsterManager* monsterMgr = MonsterManager::create();	this->addChild(monsterMgr,4);	monsterMgr->bindplayer(m_player);	m_iscore = 0;	return true;}voID TollgateScene::initBG(){	Size visibleSize = Director::getInstance()->getVisibleSize();	m_bg1 = Sprite::create("tollgateBG.jpg");	m_bg1->setposition(Point(visibleSize.wIDth/2,visibleSize.height/2));	this->addChild(m_bg1,0);	m_bg2 = Sprite::create("tollgateBG.jpg");	m_bg2->setposition(Point(visibleSize.wIDth+visibleSize.wIDth/2,visibleSize.height/2));	m_bg2->setFlippedX(true);	this->addChild(m_bg2,0);	loadUI();}voID TollgateScene::update(float delta)  //<span >开启调用update函数的功能,需要加this->scheduleUpdate()</span>{	int posX1 = m_bg1->getpositionX();	int posX2 = m_bg2->getpositionX();	int speed = 1;	posX1 -= speed;	posX2 -= speed;	m_bg1->setpositionX(posX1);	m_bg2->setpositionX(posX2);	Size mapsize = m_bg1->getContentSize();	if(posX1 <= -mapsize.wIDth/2)	{		posX1 = mapsize.wIDth + mapsize.wIDth/2;	}	if(posX2 <= -mapsize.wIDth/2)	{		posX2 = mapsize.wIDth + mapsize.wIDth/2;	}	m_bg1->setpositionX(posX1);	m_bg2->setpositionX(posX2);	m_iscore += 1;	m_scoreLab->setText(Value(m_iscore).asstring());	//m_hpbar->setPercent(100);	m_hpbar->setPercent(m_player->getiHP()/1000.0f*100);}voID TollgateScene::loadUI()//加载cocostudio的控件{	auto UI = cocostudio::GUIReader::getInstance()->WidgetFromJsonfile("littleRunnerUI_1.ExportJson");	this->addChild(UI);	auto jumpBtn = (button*)Helper::seekWidgetByname(UI,"JumpBtn");	jumpBtn->setTitleText("Jump");	jumpBtn->addtouchEventListener(this,toucheventselector(TollgateScene::jumpEvent));//跳跃动作的监听	m_scoreLab = (Text*)Helper::seekWidgetByname(UI,"scoreLab");	m_hpbar = (Loadingbar*)Helper::seekWidgetByname(UI,"Progressbar_11");}voID TollgateScene::jumpEvent(Ref*,touchEventType type){	switch(type)	{	case touchEventType::touch_EVENT_ENDED:		m_player->jump();		break;	}}

5 启动

#ifndef  _APP_DELEGATE_H_#define  _APP_DELEGATE_H_#include "cocos2d.h"/**@brIEf    The cocos2d Application.The reason for implement as private inheritance is to hIDe some interface call by Director.*/class  AppDelegate : private cocos2d::Application{public:    AppDelegate();    virtual ~AppDelegate();    /**    @brIEf    Implement Director and Scene init code here.    @return true    Initialize success,app continue.    @return false   Initialize Failed,app terminate.    */    virtual bool applicationDIDFinishLaunching();    /**    @brIEf  The function be called when the application enter background    @param  the pointer of the application    */    virtual voID applicationDIDEnterBackground();    /**    @brIEf  The function be called when the application enter foreground    @param  the pointer of the application    */    virtual voID applicationWillEnterForeground();};#endif // _APP_DELEGATE_H_#include "AppDelegate.h"#include "HelloWorldScene.h"#include "TollgateScene.h"USING_NS_CC;AppDelegate::AppDelegate() {}AppDelegate::~AppDelegate() {}bool AppDelegate::applicationDIDFinishLaunching() {    // initialize director    auto director = Director::getInstance();    auto glvIEw = director->getopenGLVIEw();    if(!glvIEw) {        glvIEw = GLVIEw::create("My Game");		glvIEw->setFrameSize(800,500);//只针对windos平台,移植到手机后这些设置是无效的。由手机屏幕来决定大小        director->setopenGLVIEw(glvIEw);    }    // turn on display FPS    director->setdisplayStats(false);    // set FPS. the default value is 1.0/60 if you don't call this    director->setAnimationInterval(1.0 / 60);    // create a scene. it's an autorelease object    auto scene = TollgateScene::createScene();    // run    director->runWithScene(scene);    return true;}// This function will be called when the app is inactive. When comes a phone call,it's be invoked toovoID AppDelegate::applicationDIDEnterBackground() {    Director::getInstance()->stopAnimation();    // if you use SimpleAudioEngine,it must be pause    // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();}// this function will be called when the app is active againvoID AppDelegate::applicationWillEnterForeground() {    Director::getInstance()->startAnimation();    // if you use SimpleAudioEngine,it must resume here    // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();}
6.不要在写代码的时候,把所有的功能都往一个类里面写,多分开几个类来写,多写一些注释,以便后面要修改或者查阅看不懂。 总结

以上是内存溢出为你收集整理的笨木头 Little Runner全部内容,希望文章能够帮你解决笨木头 Little Runner所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1079406.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存