Cocos2d_x_06 _ game _ Cannot Die

Source: Internet
Author: User

Cocos2d_x_06 _ game _ Cannot Die
Finally:



Game main scenario

//// HeroScene. h // 01_cocos2d-x // Created by beyond on 14-10-6. /// # ifndef _ HeroScene_SCENE_H __# define _ HeroScene_SCENE_H __# include "cocos2d. h "# include" GameCtrl. h "// inherit from the colorized Layerclass HeroScene: public cocos2d: LayerColor {private: // screen Size winSize; // different layers of the array correspond to different controllers cocos2d :: vector
 
  
GameCtrlArr; public: // macro-defined Create method. The init method CREATE_FUNC (HeroScene) is called internally; // The method of static cocos2d for external calls in the instantiation scenario :: scene * createScene (); // initialization method virtual bool init (); // clock method // In the Scene clock method, update \ clock method for controlling each game controller virtual void update (float dt) ;};# endif // _ HeroScene_SCENE_H __
 


//// HeroScene. h // 01_cocos2d-x // Created by beyond on 14-10-6. //// # include "HeroScene. h "# include" GameOverScene. h "USING_NS_CC; # pragma mark-lifecycle method Scene * HeroScene: createScene () {// use the cocos2d built-in physical Engine auto scene = Scene: createWithPhysics (); // display the edge of the Rigid Body for debugging // scene-> getPhysicsWorld ()-> setDebugDrawMask (PhysicsWorld: DEBUGDRAW_ALL); // adjust the gravity acceleration scene-> getPhysicsWorld () -> setGravity (Vec2 (0,-1000 )); // The Standard Code creates a Layer using the static create method, adds it to the scenario, and returns the scenario auto layer = HeroScene: create (); scene-> addChild (layer ); return scene;} // instantiate the special object bool HeroScene: init () {// create a white Layer if (! LayerColor: initWithColor (Color4B (255,255,255,255) return false; // screen size winSize = Director: getInstance ()-> getVisibleSize (); log ("winSize: % f, % f ", winSize. width, winSize. height); // create two GameCtrl (Layer 2) gameCtrlArr. insert (0, GameCtrl: create (this, 30); if (rand () % 2 = 0) {gameCtrlArr. insert (0, GameCtrl: create (this, 250);} // enable message scheduling scheduleUpdate (); //************************************** *** * ** // Physical collision detection "PhysicsContact" auto listener = EventListenerPhysicsContact: create (); // starts hitting the game to end listener-> onContactBegin = [this] (PhysicsContact & contact) {// Cancel message scheduling this-> unscheduleUpdate (); // switch to Game Over scenario ctor: getInstance ()-> replaceScene (GameOverScene: createScene ()); return true;}; // register the listener ctor: getInstance ()-> getEventDispatcher ()-> addEventListenerWithSceneGraphPr to the event distributor. Iority (listener, this ); //************************************** * ***** // the user's single-touch jump high [TouchOneByOne] auto touchListener = EventListenerTouchOneByOne:: create (); // start to Touch the in-situ jump touchListener-> onTouchBegan = [this] (Touch * t, Event * e) {// each game controller executes the for (auto it = gameCtrlArr. begin (); it! = GameCtrlArr. end (); it ++) {// obtain the array member object by unreferencing it. // if it is at its own layer, the high jump action is executed. if (* it) -> hitTestPoint (t-> getLocation () {(* it)-> onUserTouch (); break ;}return false ;}; // to the event distributor, register listener Director: getInstance ()-> getEventDispatcher ()-> addEventListenerWithSceneGraphPriority (touchListener, this); return true ;}# pragma mark-clock method void HeroScene :: update (float dt) {// update \ The clock method that controls each game controller in the scenario's clock method (Auto it = gameCtrlArr. begin (); it! = GameCtrlArr. end (); it ++) {// obtain the array member object by unreferencing it. // enable the clock method for each game controller (* it) -> startUpdate (dt );}}


Scene at the end of the game
/// GameOverScene. h // 01_cocos2d-x // Created by beyond on 14-10-6. // # include
 
  
# Include "MainScene. h "using namespace cocos2d; // inherit from the colored Layerclass GameOverScene: public LayerColor {private: Size winSize; public: // for external calls static Scene * createScene () {auto s = Scene: create (); auto l = GameOverScene: create (); s-> addChild (l); return s ;}; // The macro-defined Create method, which calls the init method CREATE_FUNC (GameOverScene) internally; // initialization, and uses the virtual bool init () {// The init method of the parent class LayerColor :: initWithColor (Color4B: WHITE); // screen size winSize = Director: getInstance ()-> getVisibleSize (); // create a Label auto label = Label :: create (); label-> setString ("Game Over"); label-> setSystemFontSize (40); label-> setName ("label"); label-> setColor (Color3B:: BLACK); label-> setPosition (winSize. width/2, winSize. height/2); // Add to Layer addChild (label); // Add an event and click Label to return the event to the main scenario. // 2. touch the Label to enable the clock updatePosition // instantiate a touch listener object auto listener = EventListenerTouchOneByOne: create (); // bind a closure function when the touch starts; // [] indicates the external object to be passed in. this // () indicates the parameter listener-> onTouchBegan = [this] (Touch * t, Event * e) {// If a label is clicked, the update location method Label * label = (Label *) e-> getCurrentTarget ()-> getChildByName ("label") is executed once every second "); if (label-> getBoundingBox (). containsPoint (t-> getLocation () {// return to the main scenario // create a scenario and automatically release it's an autorelease object auto scene = MainScene: createScene (); // replace scene Director: getInstance ()-> replaceScene (scene);} return false ;}; // 5. Get the event distributor and add an event listener, to this, listen to the [entire Layer] ctor: getInstance ()-> getEventDispatcher ()-> addEventListenerWithSceneGraphPriority (listener, this) of this object ); return true ;};};
 


A game controller instance corresponds to a layer of sub-game ]
//// GameCtrl. h // 01_cocos2d-x // Created by beyond on 14-10-6. /// # ifndef ___ export cocos2d_x _ GameCtrl __# define ___ export cocos2d_x _ GameCtrl __# include
 
  
// Full screen border # include "Boundary. h "# include" Hero. h "# include" Block. h "USING_NS_CC; // inherits from Ref and automatically has the release mechanism class GameCtrl: public Ref {private: // screen Size winSize; // border, remember with member variables because Boundary * boundary; Hero * hero is used for collision detection; // important ~~~ Layer is equivalent to the HeroScene scenario. Because all sub-Elves are added to the Layer, You need to input Layer/member variables to remember (used in other methods) Layer * _ layer; float _ positionY; // temporary variable used to accumulate the time elapsed int tempTimeDelta; // The total interval (that is, when the time delta accumulates to this interval, create and add an obstacle) int totalIntervalTime; private: // after each new obstacle is added, You need to reset the Variable void resetTempTimeDelta () for accumulative record elapsed time; // every random time, create and add an obstacle void addBlock (); public: // important ~~~ This Layer is equivalent to the HeroScene scenario, because all sub-Elves are added to the Layer, therefore, the Layer // parameter must be input to the screen's y value // for external static GameCtrl * create (Layer * layer, float positionY ); // initialize virtual bool init (Layer * layer, float positionY) by yourself; // it is called by the scenario to enable and disable the clock method void startUpdate (float dt) in the game controller ); // call it when it is touched by the user and give the hero an upward speed void onUserTouch (); bool hitTestPoint (Vec2 point );}; # endif/* defined (___ export cocos2d_x _ GameCtrl __)*/
 


//// GameCtrl. cpp // 01_cocos2d-x // Created by beyond on 14-10-6. //// # include "GameCtrl. h "// important ~~~ This Layer is equivalent to the HeroScene scenario. Because all the sub-Elves are added to the Layer, You need to input the Layer // parameter to the screen's y value // for the external GameCtrl * GameCtrl :: create (cocos2d: Layer * layer, float positionY) {auto gameCtrl = new GameCtrl (); // call your own init initialization and pass the parameters to gameCtrl-> init (layer, positionY); // automatically release gameCtrl-> autorelease (); return gameCtrl;} // initialize bool GameCtrl: init (cocos2d: Layer * layer, float positionY) {// member variable remember, other methods need to use _ layer = layer; _ positionY = positionY; // full screen winSize = Director: getInstance ()-> getVisibleSize (); //************************************** // 1. Add the border and boundary of the game = Boundary:: create (); // center (note that different Controllers may have different y values and heights on different layers) boundary-> setPosition (winSize. width/2, winSize. height/2 + positionY); // full screen boundary-> setContentSize (winSize); // Add it to Layer layer-> addChild (boundary ); //************************************** // 2. Add a floor (no need to associate with the physical world) auto ground = Sprite: create (); ground-> setColor (Color3B (0, 0, 0); ground-> setTextureRect (Rect (0, 0, winSize. width, 3); // (note that different Controllers may have different y values on different layers) 3 and 1.5 ground-> setPosition (winSize. width/2, 1.5 + positionY); // Add to Layer layer-> addChild (ground ); //************************************** // 3. Add Hero hero = Hero:: create (); // (note that different Controllers may have different y values on different layers) hero-> setPosition (50, hero-> getContentSize (). height/2 + positionY); // Add to Layer layer-> addChild (hero); // after each obstacle is added, you need to reset the variable resetTempTimeDelta (); return true ;}# pragma mark for external scenarios to call // for the scenario to call, let the scene enable and disable the clock method void GameCtrl: startUpdate (float dt) {// temporary variable, used to accumulate the recorded elapsed time tempTimeDelta ++; // total time interval (that is, when the time delta accumulates to this interval, an obstacle is created and added) if (tempTimeDelta> = totalIntervalTime) {// after each obstacle is added, you need to reset the variable resetTempTimeDelta () for accumulative record elapsed time; // at random intervals, create and add an obstacle addBlock ();}} // after a new obstacle is added, You need to reset the void GameCtrl: resetTempTimeDelta () {tempTimeDelta = 0; totalIntervalTime = (rand () % 120) + 100;} // create and add obstacles (after a random interval) void GameCtrl: addBlock () {auto B = Block: create (); _ layer-> addChild (B ); // note that the y value of the obstacle is the same as the y value of the current game controller. // that is, the half height of the block + the y B of the current controller-> setPositionY (B-> getContentSize (). height/2 + _ positionY) ;}# pragma mark-touch event // called when the user is touched, giving the hero an upward speed void GameCtrl: onUserTouch () {hero-> getPhysicsBody ()-> setVelocity (Vec2 (0,400);} bool GameCtrl: hitTestPoint (cocos2d: Vec2 point) {return boundary-> getBoundingBox (). containsPoint (point );}


Border and border
//// Boundary. h // 01_cocos2d-x // Created by beyond on 14-10-6. /// border and Boundary, whose size is the same as winSize # ifndef _ Boundary __# define _ Boundary __# include
 
  
USING_NS_CC; class Boundary: public Node {public: // macro defines a static create method. The init method CREATE_FUNC (Boundary) is called internally ); // initialization method virtual bool init () ;}; # endif/* defined (_ Boundary __)*/
 


//// Boundary. h // 01_cocos2d-x // Created by beyond on 14-10-6. //// border and border. The size is the same as that of winSize # include "Boundary. h "bool Boundary: init () {// The init method of the parent class, returns a true Node: init (); // 960*640 Size winSize = Director:: getInstance ()-> getVisibleSize (); // set Node size full screen setContentSize (winSize); // set the physical rigid body, the same size as winSize setPhysicsBody (PhysicsBody :: createEdgeBox (winSize); return true ;}


Hero protagonist
//// Hero. h // 01_cocos2d-x // Created by beyond on 14-10-6. /// main character, inherited from Sprite, running villain # ifndef ___ character cocos2d_x _ Hero __# define ___ character cocos2d_x _ Hero __# include
 
  
USING_NS_CC; class Hero: public Sprite {public: // macro. The static create method calls the init method CREATE_FUNC (Hero); virtual bool init ();}; # endif/* defined (___ 1_cocos2d_x _ Hero __)*/
 


//// Hero. cpp // 01_cocos2d-x // Created by beyond on 14-10-6. /// main character, inherited from Sprite, running villain # include "Hero. h "# include" FlashTool. h "bool Hero: init () {// init method of the parent class Sprite: init (); // The execution Frame Animation keeps running RepeatForever runAction (RepeatForever :: create (FlashTool: animateFromJsonFile ("Hero. json ", 0.2f); // Json Size s = Size (44, 52); // The sprite Size setContentSize (s ); // set the physical world's rigid body setPhysicsBody (PhysicsBody: createB Ox (s); // The rigid body cannot rotate getPhysicsBody ()-> setRotationEnable (false); // important ~~~ To participate in a collision, you must bind a collision ID getPhysicsBody ()-> setContactTestBitmask (1); return true ;}


Obstacle
//// Block. h // 01_cocos2d-x // Created by beyond on 14-10-6. /// # ifndef ___ ‑cocos2d_x _ Block __# define ___ ‑cocos2d_x _ Block __# include
 
  
USING_NS_CC; class Block: public Sprite {public: // macro. The static create method calls the init method CREATE_FUNC (Block); virtual bool init (); // The clock method, internal obstacle will constantly move virtual void update (float dt) ;};# endif/* defined (___ define cocos2d_x _ Block __)*/
 


//// Block. cpp // 01_cocos2d-x // Created by beyond on 14-10-6. //// # include "Block. h "bool Block: init () {// init method of the parent class Sprite: init (); // screen Size winSize = Director: getInstance () -> getVisibleSize (); // setPositionX (winSize. width); // setColor (Color3B (0, 0, 0); Size size Size = Size (rand () % 20) + 5, (rand () % 30) + 10); // randomly generate setContentSize (size) for obstacles of different sizes; // setTextureRect (Rect (0, 0, size. width, size. height )); //************************************** * // set the physical Rigid Body setPhysicsBody (PhysicsBody:: createBox (size); // It is not a dynamic rigid body. That is, it is a static rigid body. getPhysicsBody ()-> setDynamic (false); // important ~~~ To participate in a collision, you must bind a collision ID getPhysicsBody ()-> setContactTestBitmask (1 ); //************************************** * // enable the clock method scheduleUpdate (); return true ;}# pragma mark-clock method // The clock method, which constantly moves the obstacle left by void Block: update (float dt) {this-> setPositionX (getPositionX ()-8); // when moving outside the screen, the message scheduling is stopped and if (getPositionX () <0) {unscheduleUpdate () is removed (); removeFromParent ();}}


Parse the Json file + large image exported by flash cc,

Generate an animation object for executing a sequence frame animation.


//// FlashTool. h // 01_cocos2d-x // Created by beyond on 14-10-6. /// # ifndef ___ export cocos2d_x _ FlashTool __# define ___ export cocos2d_x _ FlashTool __# include
 
  
USING_NS_CC; class FlashTool {public: // parse the Json file + large image exported by flash cc to generate an animation object, which is used to execute the static animation * animateFromJsonFile (std :: string jsonFile, float delayPerUnit) ;};# endif/* defined (___ define cocos2d_x _ FlashTool __)*/
 


//// FlashTool. cpp // 01_cocos2d-x // Created by beyond on 14-10-6. //// # include "FlashTool. h "// Json parsing using the cocos2d built-in rapidJson library # include
 
  
// Parse the Json file and large image exported by flash cc to generate an Animate object for executing the sequential Frame Animation Animate * FlashTool: animateFromJsonFile (std: string jsonFile, float delayPerUnit) {// Document Object rapidjson: Document doc; // The FileUtils tool class reads the json file std: string fileContent = FileUtils: getInstance ()-> getStringFromFile (jsonFile ); // fileContent. erase (0, fileContent. find_first_of ('{'); // mark 0 by default and start parsing doc. parse <0> (fileContent. c_str (); // obtain the image name std of the large image.: String imgFileName = doc ["meta"] ["image"]. getString (); auto & frames = doc ["frames"]; // The auto sfc = SpriteFrameCache: getInstance (); // The container is used to store all animation frames. The Vector animFrames; // traverses, crops, creates, and adds it to the container for (auto m = frames. memberonBegin (); m! = Frames. memberonEnd (); m ++) {auto frameName = m-> name. getString (); auto & frameProperties = m-> value ["frame"]; auto & spriteSourceSize = m-> value ["spriteSourceSize"]; auto sf = sfc-> getSpriteFrameByName (frameName); if (! Sf) {sf = SpriteFrame: create (imgFileName, Rect (frameProperties ["x"]. getInt (), frameProperties ["y"]. getInt (), frameProperties ["w"]. getInt (), frameProperties ["h"]. getInt (), m-> value ["rotated"]. getBool (), Vec2 (spriteSourceSize ["x"]. getInt (), spriteSourceSize ["y"]. getInt (), Size (spriteSourceSize ["w"]. getInt (), spriteSourceSize ["h"]. getInt (); sfc-> addSpriteFrame (sf, frameName);} animFrames. pushBack (AnimationFrame: create (sf, delayPerUnit, ValueMapNull);} // generates the Animate Animation * animation = Animation: create (animFrames, delayPerUnit) for Action; return Animate:: create (animation );}
 


Json file exported by flash cc + large image


{"frames": {"hero0000":{"frame": {"x":0,"y":0,"w":44,"h":52},"rotated": false,"trimmed": false,"spriteSourceSize": {"x":0,"y":0,"w":44,"h":52},"sourceSize": {"w":44,"h":52}},"hero0001":{"frame": {"x":44,"y":0,"w":42,"h":52},"rotated": false,"trimmed": true,"spriteSourceSize": {"x":2,"y":0,"w":44,"h":52},"sourceSize": {"w":44,"h":52}},"hero0002":{"frame": {"x":86,"y":0,"w":42,"h":52},"rotated": false,"trimmed": true,"spriteSourceSize": {"x":2,"y":0,"w":44,"h":52},"sourceSize": {"w":44,"h":52}},"hero0003":{"frame": {"x":0,"y":52,"w":42,"h":52},"rotated": false,"trimmed": true,"spriteSourceSize": {"x":2,"y":0,"w":44,"h":52},"sourceSize": {"w":44,"h":52}},"hero0004":{"frame": {"x":42,"y":52,"w":42,"h":52},"rotated": false,"trimmed": true,"spriteSourceSize": {"x":2,"y":0,"w":44,"h":52},"sourceSize": {"w":44,"h":52}}},"meta": {"app": "Adobe Flash Professional","version": "13.1.0.226","image": "Hero.png","format": "RGBA8888","size": {"w":128,"h":128},"scale": "1"}}







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.