Cocos2dx getting started games

Source: Internet
Author: User

I borrowed a wooden book from the library. The following examples are from books, which are written here only for notes ..


The game content is roughly as follows:

1. A Sprite has been running on the map, and the Sprite can jump (in fact, the map keeps rolling to the left)

2. There are gold coins on the way. If Sprite eats gold coins, the Score in the upper left corner will be ++, and a plus 15 words will appear.



1. Create Entity class Entity, which is a base class, mainly used to bind an Genie and return an genie

#ifndef Entity_H#define Entity_H#include "cocos2d.h"using namespace cocos2d;class Entity:public CCNode{public:Entity();~Entity();CCSprite* getSprite();void bindSprite(CCSprite* sprite);private:CCSprite* m_sprite;};#endif

#include "Entity.h"Entity::Entity(){m_sprite=NULL;}Entity::~Entity(){};CCSprite* Entity::getSprite(){return this->m_sprite;}void Entity::bindSprite(CCSprite* sprite){this->m_sprite=sprite;this->addChild(m_sprite);}



2. Create a player main character class, which can be jump or gold coins.

# Ifndef _ Player_H # define _ Player_H # include "cocos2d. h "# include" Entity. h "using namespace cocos2d; # define JUMP_ACTION_TAG 1; class Player: public Entity {public: Player ();~ Player (); CREATE_FUNC (Player); virtual bool init (); public: void jump (); void jumpEnd (); void hit (); // int getMoney (); CCRect getBoundingBox ();/* Get collision range */void resetData (); void actionEnd (); private: bool m_isJumping; int m_money;/* Money */}; # endif
# Include "Player. h "# include" FlowWord. h "Player: Player () {m_isJumping = false; m_money = 0;/* The initial money is 0 */} Player ::~ Player () {} bool Player: init () {return true;} void Player: jump () {if (! GetSprite () {return;} if (m_isJumping)/* if the main character is still jumping, skip the jump without repeating */{return;} m_isJumping = true;/* create action, 2 s, in-situ jump (that is, the landing location offset relative to the take-off location x 0, y offset 0), height 250, bounce count 1 */CCJumpBy * jump = CCJumpBy :: create (1.5f, ccp (),);/* callFunc is also an action to call a function */CCCallFunc * callFunc = CCCallFunc: create (this, callfunc_selector (Player: jumpEnd);/* combined action */CCActionInterval * jumpActions = CCSequence: create (jump, callFunc, NULL); runAction (jumpActions);} void Player:: jumpEnd () {m_isJumping = false;} void Player: hit () {if (getSprite () = NULL) {return ;} /* Special Effects of money addition */FlowWord * flowword = FlowWord: create (); this-> addChild (flowword); flowword-> showWord ("+ 15", getSprite () -> getPosition (); m_money + = 15;/* create four action objects */CCMoveBy * backMove = CCMoveBy: create (0.1f, ccp (-20, 0 )); CCMoveBy * forwardMove = CCMoveBy: create (0.1f, ccp (20, 0); CCRotateBy * backRotate = accept: create (0.1f,-5, 0); CCRotateBy * forwardRotate = accept :: create (0.1f, 5, 0);/* are combined into two actions (executed simultaneously) */CCSpawn * backActions = CCSpawn: create (backMove, backRotate, NULL ); CCSpawn * forwardActions = CCSpawn: create (forwardMove, forwardRotate, NULL); CCCallFunc * callFunc = CCCallFunc: create (this, callfunc_selector (Player: actionEnd )); CCActionInterval * actions = CCSequence: create (backActions, forwardActions, callFunc, NULL); // this-> stopAllActions (); // resetData (); this-> runAction (actions);} void Player: resetData () {if (m_isJumping) {m_isJumping = false;} this-> setPosition (ccp (200,500/4 )); this-> setScale (1.0f); setRotation (0);} int Player: getMoney () {return m_money;} CCRect Player: getBoundingBox () {if (getSprite () = NULL) {return CCRectMake (,);}/* because the Sprite is placed on the Player, the collision range of the Player should be checked */CCSize spriteSize = getSprite () -> getContentSize (); CCPoint entityPos = this-> getPosition (); // obtain the center point of the player // obtain the coordinate value int x = entityPos in the lower left corner of the Player. x-spriteSize.width/2; int y = entityPos. y-spriteSize.height/2; return CCRectMake (x, y, spriteSize. width, spriteSize. height);} void Player: actionEnd () {this-> setScale (1.0f); setRotation (0 );}




3. Create a monster class (gold coins) and inherit from the entity class
--

# Ifndef _ Monster_H _ # define _ Monster_H _ # include "Entity. h "# include" cocos2d. h "# include" Player. h "# include" ccMacros. h "USING_NS_CC; class Monster: public Entity {public: Monster ();~ Monster (); CREATE_FUNC (Monster); virtual bool init (); public: void show (); void hide (); void reset (); // reset the monster data bool isAlive (); // whether it is in the active status bool isCollideWithPlayer (Player * player); // checks whether it is in a collision private: bool m_isAlive;}; # endif
# Include "Monster. h" Monster: Monster () {} Monster ::~ Monster () {} bool Monster: init () {return true;} void Monster: show () {if (getSprite ()! = NULL) {this-> setVisible (true); m_isAlive = true;/* mark as activity status */} void Monster: hide () {if (getSprite ()! = NULL) {this-> setVisible (false); reset (); m_isAlive = false;/* marked as active */} void Monster: reset () {if (getSprite ()! = NULL) {/* initialize monster coordinates, width (800-2800), height (100-200) */this-> setPosition (ccp (800 + CCRANDOM_0_1 () * 2000,200-CCRANDOM_0_1 () * 100);} bool Monster: isAlive () {return m_isAlive;} bool Monster: isCollideWithPlayer (Player * player) {CCRect playerRect = player-> getBoundingBox (); CCPoint monsterPos = getPosition ();/* determine whether there is an intersection */return playerRect. containsPoint (monsterPos );}



4. Create a MonsterManger class to manage the display and hiding of monsters.


# Ifndef _ MonsterManger_H __# define _ MonsterManger_H __# include "cocos2d. h "# include" Player. h "USING_NS_CC; # define MAX_MONSTER_NUM 10 class MonsterManger: public CCNode {public: MonsterManger ();~ MonsterManger (); CREATE_FUNC (MonsterManger); virtual bool init (); virtual void update (float dt);/* rewrite the update function */void bindPlayer (Player * player); private: void createMonsters ();/* create a Monster object */private: CCArray * m_monsterArr;/* store the Monster array */Player * m_player;}; # endif

# Include "MonsterManger. h" # include "Monster. h" MonsterManger: MonsterManger () {} MonsterManger ::~ MonsterManger () {} bool MonsterManger: init () {bool bRet = false; do {createMonsters ();/* create a monster */this-> scheduleUpdate (); /* enable update */bRet = true;} while (0); return bRet;} void MonsterManger: createMonsters () {m_monsterArr = CCArray: create (); m_monsterArr-> retain ();/* prevent array from being released */Monster * monster = NULL; CCSprite * sprite = NULL; for (int I = 0; I
 
  
BindSprite (CCSprite: create ("monster.png"); monster-> reset (); this-> addChild (monster);/* Add monsters to the Manager (CCNode) */m_monsterArr-> addObject (monster);/* added to the array for ease of management */} void MonsterManger: update (float dt) {CCObject * obj = NULL; monster * monster = NULL; CCARRAY_FOREACH (m_monsterArr, obj)/* traverse the monster array cyclically, repeatedly appearing on the screen */{Monster = (Monster *) obj; if (monster-> isAlive ()/* activity status */{monster-> setPositionX (monster-> getPositionX ()-3 ); // shift left if (monster-> getPositionX () <0) {monster-> hide ();} else if (monster-> isCollideWithPlayer (m_player )) {m_player-> hit (); monster-> hide () ;}} else/* inactive state */{monster-> show (); // }}} void MonsterManger:: bindPlayer (Player * player) {this-> m_player = player; this-> m_player-> retain (); // reference count + 1}
 



5. Create text floating effect (Show "+ 15" Special Effects on the main character)

#ifndef __FlowWord_H__#define __FlowWord_H__#include "cocos2d.h"USING_NS_CC;class FlowWord:public CCNode{public:FlowWord();~FlowWord();CREATE_FUNC(FlowWord);virtual bool init();public:void showWord(const char* text, CCPoint pos);void flowEnd();private:CCLabelTTF* m_textLab;};#endif


# Include "FlowWord. h" FlowWord: FlowWord () {} FlowWord ::~ FlowWord () {} bool FlowWord: init () {m_textLab = CCLabelTTF: create ("", "Arial", 30); m_textLab-> setColor (ccc3 (255, 0, 0); m_textLab-> setVisible (false); this-> addChild (m_textLab); return true;} void FlowWord: showWord (const char * str, CCPoint pos) {m_textLab-> setString (str); m_textLab-> setPosition (pos); m_textLab-> setAnchorPoint (ccp (1, 0); m_textLab-> setVisible (true ); // zoom in and zoom out CCActionInterval * scaleLarge = CCScaleTo: create (0.3f, 2.5f, 2.5f); CCActionInterval * scaleSmall = CCScaleTo: create (0.4f, 0.5f, 0.5f ); // callback action, removing the result CCCallFunc * callFunc = CCCallFunc: create (this, callfunc_selector (FlowWord: flowEnd); CCActionInterval * actions = CCSequence: create (scaleLarge, scaleSmall, callFunc, NULL); m_textLab-> runAction (actions);} void FlowWord: flowEnd () {m_textLab-> setVisible (false);/* true: Remove from parent node, and remove the node action and callback function */m_textLab-> removeFromParentAndCleanup (true );}

6. Create a game scenario class, where all the effects of the game are displayed.

# Ifndef _ toll1_scene_h __# define _ toll1_scene_h __# include "cocos2d. h "# include" cocos-ext.h "# include" Player. h "using namespace cocos2d; using namespace cocos2d: extension; class toll1_scene: public CCLayer {public: static CCScene * scene (); virtual bool init (); CREATE_FUNC (toll1_scene ); virtual void update (float delta); private: void initBG ();/* initialize the level background */void createJumpBtn (); /* Create jump button */void jumpEvent (CCObject * pSender, CCControlEvent event);/* Click event */void createScoreLab () in the response button (); /* Create score tag */void createTimeSlider ();/* create time entry */private: CCSprite * m_bgSprite1; CCSprite * m_bgSprite2; Player * m_player; CCLabelTTF * m_scoreLab; // score tag CCControlSlider * m_TimeSlider; // int m_score;/* score */int m_curTime;/* current time */}; # endif

# Include "toll1_scene. h "# include" MonsterManger. h "CCScene * toll1_scene: scene () {CCScene * scene = NULL; do {scene = CCScene: create (); CC_BREAK_IF (! Scene); toll1_scene * layer = toll1_scene: create (); CC_BREAK_IF (! Layer); scene-> addChild (layer, 1);} while (0); return scene;} bool toll1_scene: init () {bool bRet = false; do {CCSize visibleSize = CCDirector: shareddire()-> getVisibleSize ();/* game title image * // CCSprite * titleSprite = CCSprite: create ("title.png "); // titleSprite-> setPosition (ccp (visibleSize. width/2, visibleSize. height-50); // this-> addChild (titleSprite, 2);/* create pig */CCSprite * sprite = CCSprite: create ("sprite.png "); // sprite-> setFlipX (true); m_player = Player: create (); m_player-> bindSprite (sprite); m_player-> setPosition (ccp (200, visibleSize. height/4); this-> addChild (m_player, 1);/* initialize the background image */initBG ();/* Create button */createJumpBtn (); /* set to enable the update () function of CCNode. The game calls the update () function */this-> scheduleUpdate () at each frame (); /* create a monster Manager (with many monsters in the Manager) */MonsterManger * monsterManger = MonsterManger: create (); monsterManger-> bindPlayer (m_player ); this-> addChild (monsterManger, 4);/* Create score tag */createScoreLab ();/* create time entry */createTimeSlider (); bRet = true ;} while (0); return bRet;} void toll1_scene: initBG () {CCSize visibleSize = CCDirector: sharedDirector ()-> getVisibleSize (); m_bgSprite1 = CCSprite :: create ("tollgateBG.jpg"); m_bgSprite1-> setPosition (ccp (visibleSize. width/2, visibleSize. height/2); this-> addChild (m_bgSprite1, 0); m_bgSprite2 = CCSprite: create ("tollgateBG.jpg"); m_bgSprite2-> setPosition (ccp (visibleSize. width + visibleSize. width/2, visibleSize. height/2); m_bgSprite2-> setFlipX (true); this-> addChild (m_bgSprite2, 0);} void toll1_scene: update (float delta) {CCSize mapSize = m_bgSprite1-> getContentSize (); // map size int posX1 = m_bgSprite1-> getPositionX (); // map 1 x coordinate int posX2 = m_bgSprite2-> getPositionX (); // map 2 x coordinate int iSpeed = 2; // map rolling speed posX1-= iSpeed; // scroll from two locations to the left. posX2-= iSpeed; // create an infinite loop if (posX1 <=-mapSize. width/2) {posX1 = mapSize. width + mapSize. width/2; posX2 = mapSize. width/2;} if (posX2 <=-mapSize. width/2) {posX1 = mapSize. width/2; posX2 = mapSize. width + mapSize. width/2;} m_bgSprite1-> setPositionX (posX1); m_bgSprite2-> setPositionX (posX2);/* increase the score */m_score = m_player-> getMoney (); m_scoreLab-> setString (CCString: createWithFormat ("Score: % d", m_score)-> getCString (); m_TimeSlider-> setValue (-- m_curTime);} void toll1_scene :: createJumpBtn () {CCSize visibleSize = CCDirector: shareddire()-> getVisibleSize ();/* button title */CCLabelTTF * jumpLabel = CCLabelTTF: create ("Jump ", "Arial", 35);/* button status image */CCScale9Sprite * jumpNorBG = CCScale9Sprite: create ("button.png"); CCScale9Sprite * jumpLightBG = CCScale9Sprite :: create ("buttonHighlighted.png");/* create button */CCControlButton * jumpBtn = CCControlButton: create (jumpLabel, jumpNorBG); jumpBtn-> setPosition (ccp (visibleSize. width-80, 50); jumpBtn-> events (jumpLightBG, CCControlStateHighlighted);/* Add event */jumpBtn-> events (this, cccontrol_selector (toll1_scene: jumpEvent ), CCControlEventTouchDown); this-> addChild (jumpBtn);} void toll1_scene: jumpEvent (CCObject * pSender, CCControlEvent event) {m_player-> jump ();} void toll1_scene :: createScoreLab () {m_score = m_player-> getMoney (); CCSize visibleSize = ccctor ctor: shareddire()-> getVisibleSize (); m_scoreLab = CCLabelTTF: create ("Score: "+ m_score," Arial ", 35); m_scoreLab-> setAnchorPoint (ccp (0, 1); m_scoreLab-> setPosition (ccp (0, visibleSize. height); this-> addChild (m_scoreLab);} void toll1_scene: createTimeSlider () {CCSize visibleSize = CCDirector: shareddire()-> getVisibleSize (); m_curTime = 10000; m_TimeSlider = CCControlSlider: create (CCSprite: create ("background.png"), CCSprite: create ("progress.png"), CCSprite: create ("sliderThumb.png ")); m_TimeSlider-> setPosition (ccp (m_TimeSlider-> getContentSize (). width/2, visibleSize. height-m_TimeSlider-> getContentSize (). height-m_scoreLab-> getContentSize (). height); m_TimeSlider-> setTouchEnabled (false); m_TimeSlider-> setMaximumValue (10000); m_TimeSlider-> setMinimumValue (0); m_TimeSlider-> setValue (m_curTime ); this-> addChild (m_TimeSlider, 3 );}



The running effect is as follows:

Source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.