Cocos2d-x 2.3.3 Version Flappybird

Source: Internet
Author: User
Tags addchild

cocos2d-x 2.3.3 Version Flappybird

this blog, based on Cocos2d-x 2.3.3, describes how to develop a game flappybird that was very hot before. This blog content outline is as follows: 1. How to create a cocos2d-x 2.3.3 Project 2. Initializing the physical world of box2d and simulating the physical world3. How to add a bird to the physical world4. How to add flooring5. Adding water pipes6. Collision Detection7. This paper summarizes
:1. How to create Cocos2d-x 2.3.3This blog is based on Cocos2d-x 2.3.3, beginners can choose this version to learn, but also can learn from the 3.x version, but the version difference is larger. to enter directory D:\cocos2d-x-2.2.3\tools\project-creator with the command line, create the project by typing the following command:python create_project.py-project flappybirdcpp-package com.wwj.flappybird-language cpp
a cocos2d-x project named Flappybirdcpp was created with the package name Com.wwj.flappybird and the development language C + +

2. Initializing the physical world of box2d and simulating the physical worldCocos2d-x uses the box2d physics engine to simulate the physical world, and it also supportsChipmunk Physics engine, here we use box2d to create a seemingly more real world for us.
-10 means the gravitational acceleration direction is down world = new B2world (B2VEC2 (0,-10));


Simulated physical World//box2d The recommended iteration count is the speed stage 8 times, the position Stage 3 times world->step (DT, 8, 3);

3. How to add a bird to the physical worldbirds in the cocos2d-x is a sprite, we know that the Elves need to be added to the layer, we also set our birds in the physical world of rigid bodies. About box2d related concepts, the author does not elaborate here, readers can find their own Baidu teacher, learn more about box2d knowledge. we define the following methods:
/*** Add bird **/void Helloworld::addbird () {//create bird bird = B2sprite::create ("Bird.png");//get content size ccsize size = bird-> Getcontentsize ();//Rigid Body Properties b2bodydef bodydef;//Dynamic rigid body Bodydef.type = b2_dynamicbody;//Set initial position bodydef.position = B2VEC2 ( Screensize.width/2/ratio, screensize.height/2/ratio);//Create a bird rigid body b2body *birdbody = world->createbody (& BODYDEF)///Stealth shape B2polygonshape birdshape;//set to box, parameter is content half width half height birdshape.setasbox (size.width/2/ratio, size.height/2/ RATIO);//material Properties B2fixturedef birdfixturedef;//shape Birdfixturedef.shape = &birdshape;//Add Ground object birdbody-> Createfixture (&birdfixturedef);//Set Measure scale bird->setptmratio (RATIO);//Set bird rigid body bird->setb2body (birdbody);// Add a bird to the layer of addchild (bird);}


4. How to add flooringThe floor and the bird are similar, just set the floor rigid body type is static, because it is relatively static and not affected by gravity.
/*** Add Floor */void helloworld::addground () {//floor genie B2sprite *ground = b2sprite::create ("Ground.png");//Get the size of floor content ccsize Size = Ground->getcontentsize ();//used to initialize some properties of the rigid body in the physical world, such as position, type b2bodydef bdef;//static rigid body Bdef.type = b2_staticbody;// Set Position bdef.position = B2VEC2 (Size.width/2/ratio, size.height/2/ratio);//create rigid body b2body *groundbody = world->createbody ( &BDEF);//Shape B2polygonshape groundshape;//set to Rectangular groundshape.setasbox (Size.width/2/ratio, Size.height/2/RATIO); /material customizer b2fixturedef groundfixturedef;//set Shape Groundfixturedef.shape = &groundshape;//Create Customizer groundbody-> Createfixture (&groundfixturedef);//Set Rigid body ground->setb2body (groundbody) for sprites;//Set Measure scale ground->setptmratio ( RATIO);//Add floor to layer addchild (ground);}

5. Adding water pipeswhen we play flappybird, we will know that the pipe height is different, then from right to left to move, which requires us to randomly set up and down two water pipe location, and constantly add water pipes.
/Add the movement of the Water pipe void Helloworld::addbar (float dt) {//randomly generated offsets float offset =-rand ()%5;//Create a down water pipe for the genie b2sprite *down_bar = b2sprite: : Create ("down_bar.png");//Get the size of the water pipe ccsize down_bar_size = down_bar->getcontentsize ();//Lower pipe b2bodydef down_bar_body _def;//kinematic object, but not affected by gravity Down_bar_body_def.type = b2_kinematicbody;//Setting the position of the water pipe down_bar_body_def.position = B2VEC2 ( Screensize.width/ratio + 2, DOWN_BAR_SIZE.HEIGHT/RATIO/2 +offset);//linear speed, moving from right to left down_bar_body_def.linearvelocity = B2VEC2 ( -5,0);//create rigid body b2body *down_bar_body = world->createbody (&down_bar_body_def);//Stealth Shape B2polygonshape Down_ The bar_shape;//is set to the box, and the parameters are half-width and half-height down_bar_shape content. Setasbox (Down_bar_size.width/2/ratio, down_bar_size.height/2/ratio);//Declaration customizer B2fixturedef down_bar_fixture_def;// Customizer Shape Down_bar_fixture_def.shape = &down_bar_shape;//Creates a customizer for a rigid body down_bar_body->createfixture (&down_bar_ FIXTURE_DEF);//Set Elf rigid body down_bar->setb2body (down_bar_body);//Set Metric down_bar->setptmratio (RATIO);//Upper Pipe b2sprite *up_bar = B2sprite::create ("Up_bar.png");//Get content size ccsize up_bar_size = up_bar->getcontentsize () b2bodydef up_bar_body_def;//kinematic object, but not affected by gravity Up_bar_body_ Def.type = b2_kinematicbody;//Set water pipe position up_bar_body_def.position = B2VEC2 (screensize.width/ratio+2, Down_bar_ Size.height/ratio+offset+2+up_bar_size.height/2/ratio); up_bar_body_def.linearvelocity = b2Vec2 ( -5, 0); B2Body *up_ Bar_body = World->createbody (&up_bar_body_def);//Stealth shape B2polygonshape up_bar_shape;//set to Box shape, parameter is half width and half height up_bar_ Shape. Setasbox (Up_bar_size.width/2/ratio, up_bar_size.height/2/ratio); B2fixturedef up_bar_fixture_def;up_bar_fixture_ Def.shape = &up_bar_shape;up_bar_body->createfixture (&up_bar_fixture_def); Up_bar->setB2Body (Up_bar _body); Up_bar->setptmratio (RATIO); Barcontainer->addchild (Down_bar); Barcontainer->addchild (Up_bar);}

6. Add Collision DetectionHere we need to say how to make the bird movement, we need to set the screen listening events, and let the bird has an upward linear speed, click on the screen when the bird upward movement, release then fall. we need to rewrite the method:
virtual void Cctouchesbegan (Ccset *ptouches, ccevent *pevent);

Realize:
Touch event start void Helloworld::cctouchesbegan (Cocos2d::ccset *ptouches, cocos2d::ccevent *pevent) {bird->getb2body ()- >setlinearvelocity (B2VEC2 (0, 5));}

Next, we're going to set up the listener for the collision detection, and we're setting up a physical-world event listener.
Add Collision Monitor World->setcontactlistener (this);


then override the following methods:
virtual void Begincontact (b2contact* contact);

void Helloworld::begincontact (B2contact *contact) {//Collide, pop-up dialog if (Contact->getfixturea ()->getbody () Getuserdata () = = Bird | | Contact->getfixtureb ()->getbody ()->getuserdata () = = Bird) {stopgame (); Ccmessagebox ("Game failed", "game Failed");}}


7. This paper summarizesthe above content is to develop a Flappybird simple demo, the reader can be based on the realization of a richer function, I do not feel like one step all things introduced. The most important is the idea, the basic things mastered, and then you can follow this way to do a thing like this. You can download the source code at the following address: Https://github.com/devilWwj/eoeFlappyBird
here is the full implementation:HelloWorldScene.h
#ifndef __helloworld_scene_h__#define __helloworld_scene_h__#include "cocos2d.h" #include "box2d\box2d.h"// Introduction of box2d physics engine # include "B2Sprite.h"//define Physical World Scale # RATIO 48.0fclass helloworld:public cocos2d::cclayer,public B2contactlistener{public://Here ' s a difference.      Method ' init ' in cocos2d-x returns BOOL, instead of the 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 ();        A selector callback void Menuclosecallback (ccobject* psender); Implement the "Static node ()" Method manually Create_func (HelloWorld); virtual void Cctouchesbegan (Ccset *ptouches, ccevent *pevent); virtual void Begincontact (b2contact* contact);//rewrite Update method virtual void update (float dt);//Declare Physical world reference B2world *world; B2sprite *bird; Ccsize screensize; Ccsprite *barcontainer;private://Add the bird void Addbird ();//Initialize the physical world void Initworld ();//Add floor void addground ();//Add water pipe void Addbar (flOat DT); Add a container void Addbarcontainer ();//start game void Startgame (float dt);//end game void Stopgame ();}; #endif//__helloworld_scene_h__

HelloWorldScene.cpp
#include "HelloWorldScene.h" USING_NS_CC; ccscene* Helloworld::scene () {//' scene ' is a autorelease objectccscene *scene = Ccscene::create ();//' layer ' is an Autore Lease Objecthelloworld *layer = Helloworld::create ();//Add layer as a child to scenescene->addchild (layer);//Return T He scenereturn scene;} On "Init" need to initialize your Instancebool helloworld::init () {////////////////////////////////1. Super init fi Rstif (! Cclayer::init ()) {return false;} Get screen Size screensize = Ccdirector::shareddirector ()->getvisiblesize (); Initworld (); Addbird (); Addbarcontainer (); Addground ();//settings can be clicked settouchenabled (true);//scheduleupdate ();//schedule (Schedule_selector (Helloworld::addbar), 1 );//3 seconds after execution of Scheduleonce (Schedule_selector (Helloworld::startgame), 3); return true;} /*** Add bird **/void Helloworld::addbird () {//create bird bird = B2sprite::create ("Bird.png");//get content size ccsize size = bird-> Getcontentsize ();//Rigid Body Properties b2bodydef bodydef;//Dynamic rigid body Bodydef.type = b2_dynamicbody;//Set initial position bodydef.position = B2Vec2 (Screensize.width/2/ratio, screensize.height/2/ratio);//Create a bird rigid body b2body *birdbody = world->createbody (& BODYDEF)///Stealth shape B2polygonshape birdshape;//set to box, parameter is content half width half height birdshape.setasbox (size.width/2/ratio, size.height/2/ RATIO);//material Properties B2fixturedef birdfixturedef;//shape Birdfixturedef.shape = &birdshape;//Add Ground object birdbody-> Createfixture (&birdfixturedef);//Set Measure scale bird->setptmratio (RATIO);//Set bird rigid body bird->setb2body (birdbody);// Add a bird to the layer of addchild (bird);} Initializing the physical World void Helloworld::initworld () {//-10 means that the gravitational acceleration direction is down world = new B2world (B2VEC2 (0,-10));//Add Collision monitoring world-> Setcontactlistener (this);} update void helloworld::update (float dt) {//Simulate physical world//box2d The recommended iteration count is the speed stage 8 times, Position Stage 3 times world->step (DT, 8, 3); Ccsprite *s;//traversal destroys for (b2body *b = World->getbodylist (); b!= NULL; B=b->getnext ()) {if (B->getposition (). x<- 3) {s = (ccsprite*) b->getuserdata (); if (s! = NULL) {s->removefromparent (); Cclog ("Remove"); World->destroybody (b);}} /*** Add Floor */void helloworld::addground () {//Floor finishLing B2sprite *ground = b2sprite::create ("Ground.png");//Get the size of the floor content ccsize sizes = ground->getcontentsize ();// Some properties used to initialize a rigid body in the physical world, such as position, type b2bodydef bdef;//static rigid body Bdef.type = b2_staticbody;//Set Position bdef.position = B2VEC2 (size.width/2/ RATIO, size.height/2/ratio);//create rigid body b2body *groundbody = world->createbody (&bdef);//Shape B2polygonshape groundshape;//is set to rectangular groundshape.setasbox (Size.width/2/ratio, size.height/2/ratio);//Material customizer B2fixturedef groundfixturedef;//Set Shape Groundfixturedef.shape = &groundshape;//Create Customizer groundbody->createfixture (& GROUNDFIXTUREDEF);//Set Rigid body ground->setb2body (groundbody) for sprites;//Set measure ratio ground->setptmratio (RATIO);// Add floor to Layer addchild (ground);} Touch event start void Helloworld::cctouchesbegan (Cocos2d::ccset *ptouches, cocos2d::ccevent *pevent) {bird->getb2body ()- >setlinearvelocity (B2VEC2 (0, 5));} Add the movement of the Water pipe void Helloworld::addbar (float dt) {//randomly generated offsets float offset =-rand ()%5;//Create a down water pipe for the genie b2sprite *down_bar = B2sprite :: Create ("down_bar.png");//Get the size of the pipe ccsize down_bar_siZe = down_bar->getcontentsize ();//Bottom pipe b2bodydef down_bar_body_def;//kinematic object, but not affected by gravity Down_bar_body_def.type = b2_ kinematicbody;//Setting the location of the water pipe down_bar_body_def.position = b2vec2 (Screensize.width/ratio + 2, down_bar_size.height/ratio/ 2 +offset);//linear speed, moving from right to left down_bar_body_def.linearvelocity = B2VEC2 ( -5,0);//create rigid body b2body *down_bar_body = world-> Createbody (&AMP;DOWN_BAR_BODY_DEF)///Stealth shape B2polygonshape down_bar_shape;//set to box, parameter is content of half width and half height down_bar_shape. Setasbox (Down_bar_size.width/2/ratio, down_bar_size.height/2/ratio);//Declaration customizer B2fixturedef down_bar_fixture_def;// Customizer Shape Down_bar_fixture_def.shape = &down_bar_shape;//Creates a customizer for a rigid body down_bar_body->createfixture (&down_bar_ FIXTURE_DEF);//Set Elf rigid body down_bar->setb2body (down_bar_body);//Set Metric down_bar->setptmratio (RATIO);//Upper Pipe b2sprite *up_bar = B2sprite::create ("Up_bar.png");//Get content size ccsize up_bar_size = Up_bar->getcontentsize (); B2BodyDef Up_bar_ body_def;//kinematic object, but not affected by gravity Up_bar_body_def.type = b2_kinematicbody;//set water pipe position Up_bar_body_def.position = b2vec2 (screensize.width/ratio+2, down_bar_size.height/ratio+offset+2+up_bar_size.height/2/ratio); up_bar_body_ def.linearvelocity = b2vec2 ( -5, 0); B2body *up_bar_body = World->createbody (&up_bar_body_def);// The invisible shape B2polygonshape up_bar_shape;//is set to the box shape and the parameter is half width and half height up_bar_shape. Setasbox (Up_bar_size.width/2/ratio, up_bar_size.height/2/ratio); B2fixturedef up_bar_fixture_def;up_bar_fixture_ Def.shape = &up_bar_shape;up_bar_body->createfixture (&up_bar_fixture_def); Up_bar->setB2Body (Up_bar _body); Up_bar->setptmratio (RATIO); Barcontainer->addchild (Down_bar); Barcontainer->addchild (Up_bar);} The container of the movement bar is void Helloworld::addbarcontainer () {Barcontainer = Ccsprite::create (); AddChild (Barcontainer);} Start game void Helloworld::startgame (float dt) {scheduleupdate (); Schedule (Schedule_selector (Helloworld::addbar), 1);} End game void Helloworld::stopgame () {unscheduleupdate (); Unschedule (Schedule_selector (Helloworld::addbar));} void Helloworld::begincontact (B2contact *contact) {//Collide, the popup dialog box if (Contact->getfixturea ()->getbody ()->getuserdata () = = Bird | | Contact->getfixtureb ()->getbody ()->getuserdata () = = Bird) {stopgame (); Ccmessagebox ("Game failed", "game Failed");}} 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"); #elseCCDirector:: Shareddirector ()->end (); #if (cc_ Target_platform = = Cc_platform_ios) exit (0); #endif #endif}


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.