用cocos2d-x 3.2 实现的FlappyBird

来源:互联网 发布:制作婚礼视频软件 编辑:程序博客网 时间:2024/05/21 21:38

最近才开始学cocos2dx,买了几本书还有看大神(主要是 笨木头)的博客。然后就自己尝试用cocos2d-x实现了一下...

(新手,勿喷...)

先看运行效果 http://pan.baidu.com/s/1hqBsCYS

转载请注明出处:http://blog.csdn.net/joueu



你看那只笨鸟好逼真啊(其实是叫FlappyRect啦)


TollgateScene.cpp

////  TollgateScene.cpp//  FlappyRect////  Created by Joueu on 14-10-7.////#include "TollgateScene.h"#include "Pipe.h"#include "shareHeader.h"#include "MenuScene.h"bool TollgateScene::init(){    if (!Layer::init()) {        return false;    }        createOprUI();            Size visibleSize = Director::getInstance() -> getVisibleSize();    Point visiblePoint = Director::getInstance() -> getVisibleOrigin();    m_bird = Bird::create();    m_bird -> setPosition(visibleSize.width * 0.2f, visibleSize.height * 0.5f);    this -> addChild(m_bird);        m_pipesLayer = PipesLayer ::create();    m_pipesLayer -> setPosition(0, 170);    this -> addChild(m_pipesLayer);        schedule(schedule_selector(TollgateScene::logic));    //    auto contactListener = EventListenerPhysicsContact::create();//    contactListener -> onContactBegin = CC_CALLBACK_1(TollgateScene::onContactBegin, this);//    _eventDispatcher -> addEventListenerWithSceneGraphPriority(contactListener, this);        auto contactListener = EventListenerPhysicsContact::create();    contactListener -> onContactBegin = CC_CALLBACK_1(TollgateScene::onContactBegin, this);    _eventDispatcher -> addEventListenerWithSceneGraphPriority(contactListener, this);    return true;}void TollgateScene::createOprUI(){    Node *UI = timeline::NodeReader::getInstance() -> loadNodeWithFile("Flappy_1.ExportJson");    m_flyBtn = (Button *)Helper::seekWidgetByName((Widget *)UI, "flyBtn");    m_flyBtn -> addTouchEventListener(this, toucheventselector(TollgateScene::flyBtnPressed));        Size btnSize = Size(640,210);    PhysicsBody *body = PhysicsBody::createBox(btnSize);    body -> setDynamic(false);    body -> setCollisionBitmask(1);    body -> setCategoryBitmask(1);    body -> setContactTestBitmask(1);    m_flyBtn -> setPhysicsBody(body);//    m_bg1 = (Sprite *)Helper::seekWidgetByName((Widget *)UI, "borderImg");        m_bg1 =(Sprite *) UI -> getChildren().at(2);    m_bg2 = Sprite::create("border.png");    m_bg2 -> setPosition(960,m_bg1 -> getPositionY());        this -> addChild(m_bg2);    this -> addChild(UI);}void TollgateScene::flyBtnPressed(Ref *sender,TouchEventType type){    switch (type) {        case TouchEventType::TOUCH_EVENT_ENDED:            m_bird -> jump();            break;                    default:            break;    }}Scene *TollgateScene::scene(){        Scene *scene = Scene::createWithPhysics();        Vect gravity(0,-500.0f);        scene -> getPhysicsWorld() -> setGravity(gravity);        TollgateScene *layer = TollgateScene::create();        scene -> addChild(layer);        return scene;}void TollgateScene::logic(float dt){    int PosX1 = m_bg1 -> getPositionX();    int PosX2 = m_bg2 -> getPositionX();        int iSpeed = 4;        PosX1 -= iSpeed;    PosX2 -= iSpeed;        int visibleWidth = Director::getInstance() -> getVisibleSize().width;        if (PosX1 < - 0.5f * visibleWidth) {        PosX2 = 0.5f * visibleWidth;        PosX1 = 1.5f * visibleWidth;    }    if (PosX2 < -0.5f * visibleWidth) {        PosX1 = 0.5f * visibleWidth;        PosX2 = 1.5f * visibleWidth;    }        m_bg1 -> setPositionX(PosX1);    m_bg2 -> setPositionX(PosX2);}TollgateScene::~TollgateScene(){    }bool TollgateScene::onContactBegin(PhysicsContact &contact){    auto nodeA =(Sprite *) contact.getShapeA() -> getBody() -> getNode();    auto nodeB = (Sprite *)contact.getShapeB() -> getBody() -> getNode();        if (nodeA == NULL && nodeB == NULL) {        return false;    }        if ((nodeA -> getTag() == shareHeader_BirdTag && nodeB -> getTag() == shareHeader_PipeTag) ||        (nodeA -> getTag() == shareHeader_PipeTag && nodeB -> getTag() == shareHeader_BirdTag)) {        Director::getInstance() -> replaceScene(TransitionSlideInT::create(1.0f,MenuScene::scene()));    }    return true;}void TollgateScene::onExit(){    Layer :: onExit();    _eventDispatcher -> removeEventListenersForTarget(this);}

TollgateScene.h

////  TollgateScene.h//  FlappyRect////  Created by Joueu on 14-10-7.////#ifndef __FlappyRect__TollgateScene__#define __FlappyRect__TollgateScene__#include "cocos2d.h"#include "cocostudio/Cocostudio.h"#include "editor-support/cocostudio/CCSGUIReader.h"#include "ui/CocosGUI.h"#include "Bird.h"#include "PipesLayer.h"using namespace cocos2d::ui;using namespace cocostudio;USING_NS_CC;class TollgateScene : public Layer{public:    CREATE_FUNC(TollgateScene);        virtual bool init();        static Scene *scene();        ~TollgateScene();    virtual void onExit() override;private:    void flyBtnPressed(Ref *sender,TouchEventType type);    void createOprUI();    Button *m_flyBtn;    Bird *m_bird;    void logic(float dt);        Sprite *m_bg1;    Sprite *m_bg2;        PipesLayer *m_pipesLayer;        bool onContactBegin (PhysicsContact &contact);};#endif /* defined(__FlappyRect__TollgateScene__) */

PipesLayer.cpp

////  PipesLayer.cpp//  FlappyRect////  Created by Joueu on 14-10-7.////#include "PipesLayer.h"PipesLayer::PipesLayer(){    }PipesLayer::~PipesLayer(){    }bool PipesLayer::init(){//    srand(time(0));    m_TimeCount = 0;    schedule(schedule_selector(PipesLayer::logic));    return true;}int gameRand(int vMin,int vMax){    return (2.0f*random() / 0xFFFFFFFFu) * ((vMax+1)-vMin) + vMin;}void PipesLayer::logic(float dt){    Size visibleSize = Director::getInstance() -> getVisibleSize();    m_TimeCount += dt;    if (m_TimeCount > 4)    {//        log("%d",rand() % 700);//        int randomPosition = rand() % 700;        int randomPosition = gameRand(80, 600);        m_TimeCount -= 4;        Pipe *pipe = Pipe::create(randomPosition);        pipe -> setPosition(Vec2(visibleSize.width * 1.5f, this -> getContentSize().height * 0.5f));        this -> addChild(pipe);        m_vector.pushBack(pipe);    }    for (Pipe *p : m_vector){        p -> setPositionX(p -> getPositionX() - shareHeader_speed);        if (p -> getPositionX() < -visibleSize.width * 0.5) {            m_vector.eraseObject(p);//            p -> getPhysicsBody() -> removeFromWorld();            p -> removeFromParent();        }    }}

PipesLayer.h

////  PipesLayer.h//  FlappyRect////  Created by Joueu on 14-10-7.////#ifndef __FlappyRect__PipesLayer__#define __FlappyRect__PipesLayer__#include "cocos2d.h"#include "Pipe.h"#include "shareHeader.h"USING_NS_CC;class PipesLayer:public Node{public:    PipesLayer();    ~PipesLayer();    virtual bool init();    CREATE_FUNC(PipesLayer);    void logic(float dt);private:    float m_TimeCount;    Vector<Pipe *>m_vector;};#endif /* defined(__FlappyRect__PipesLayer__) */

Brid.cpp

////  Bird.cpp//  FlappyRect////  Created by Joueu on 14-10-7.////#include "Bird.h"#include "shareHeader.h"Bird::Bird(){    }Bird::~Bird(){    }bool Bird::init(){        if (!Layer::init()) {        return false;    }    this -> setTag(shareHeader_BirdTag);    Sprite *sprite = Sprite::create("rect.jpg");        Size spriteSize = sprite -> getContentSize();        this -> setContentSize(spriteSize);        PhysicsBody *body = PhysicsBody::createBox(spriteSize);    //    body -> setDynamic(false);//    body -> setRotationEnable(false);    body -> setCategoryBitmask(1);    body -> setCollisionBitmask(1);    body -> setContactTestBitmask(1);        this -> setPhysicsBody(body);    this -> addChild(sprite);        return true;}void Bird::jump(){//    this -> getPhysicsBody() -> applyImpulse(Vect(0,100000));    this -> getPhysicsBody() -> setVelocity(Vect(0,300));}


Brid.h

////  Bird.h//  FlappyRect////  Created by Joueu on 14-10-7.////#ifndef __FlappyRect__Bird__#define __FlappyRect__Bird__#include "cocos2d.h"USING_NS_CC;class Bird : public Layer{public:    Bird();    ~Bird();    CREATE_FUNC(Bird);    virtual bool init();    void jump();};#endif /* defined(__FlappyRect__Bird__) */


Pipe.cpp

<pre name="code" class="cpp">////  Pipe.cpp//  FlappyRect////  Created by Joueu on 14-10-7.////#include "Pipe.h"#include "shareHeader.h"bool Pipe::init(int randomPosition){    m_lowerPipe = Sprite::create("pipe.png");    float pipeHeight = m_lowerPipe -> getContentSize().height;    float pipeWidth = m_lowerPipe -> getContentSize().width;    m_lowerPipe -> setScaleY( (randomPosition) / pipeHeight);    m_lowerPipe -> setPosition(Vec2(pipeWidth * 0.5f, pipeHeight * 0.5f *m_lowerPipe -> getScaleY()));    this -> setContentSize(Size(pipeWidth,shareHeader_gameSceneHeight));        m_lowerPipe -> setTag(shareHeader_PipeTag);    m_upperPipe = Sprite::create("pipe.png");    m_upperPipe -> setScaleY((shareHeader_gameSceneHeight - (m_lowerPipe -> getScaleY() * pipeHeight) - shareHeader_emptyHeight)/ pipeHeight);    m_upperPipe -> setPosition(Vec2(pipeWidth * 0.5f,shareHeader_gameSceneHeight - pipeHeight * m_upperPipe -> getScaleY() * 0.5));    m_upperPipe -> setFlippedY(true);    m_upperPipe -> setTag(shareHeader_PipeTag);        PhysicsBody *lowerbody = PhysicsBody::createBox(Size(pipeWidth,pipeHeight *m_lowerPipe -> getScaleY()));    lowerbody -> setDynamic(false);    lowerbody -> setCategoryBitmask(1);    lowerbody -> setCollisionBitmask(1);    lowerbody -> setContactTestBitmask(1);    m_lowerPipe -> setPhysicsBody(lowerbody);        PhysicsBody *upperbody = PhysicsBody::createBox(Size(pipeWidth,pipeHeight *m_upperPipe -> getScaleY()));    upperbody -> setDynamic(false);    upperbody -> setCategoryBitmask(1);    upperbody -> setCollisionBitmask(1);    upperbody -> setContactTestBitmask(1);    m_upperPipe -> setPhysicsBody(upperbody);        this -> addChild(m_upperPipe);    this -> addChild(m_lowerPipe);    return true;}Pipe *Pipe::create(int randomPosition){    auto pipe = new Pipe();    if (pipe && pipe -> init(randomPosition)) {        pipe -> autorelease();    }else    {        CC_SAFE_DELETE(pipe);    }    return pipe;}Pipe::~Pipe(){}


Pipe.h

////  Pipe.h//  FlappyRect////  Created by Joueu on 14-10-7.////#ifndef __FlappyRect__Pipe__#define __FlappyRect__Pipe__#include "cocos2d.h"USING_NS_CC;class Pipe: public Node{public:    static Pipe*create(int randomPosition);    bool init(int randomPosition);    ~Pipe();private:    Sprite *m_upperPipe;    Sprite *m_lowerPipe;};#endif /* defined(__FlappyRect__Pipe__) */


MenuScene.cpp

////  MenuScene.cpp//  FlappyRect////  Created by Joueu on 14-10-7.////#include "MenuScene.h"#include "TollgateScene.h"bool MenuScene::init(){    auto visibleSize = Director :: getInstance() -> getVisibleSize();    auto labelStart = Label::create("Start Game", "Monaco", 40);    MenuItemLabel *label = MenuItemLabel::create(labelStart,CC_CALLBACK_1(MenuScene::labelPressed, this));    auto menu = Menu::create(label, NULL);    this -> addChild(menu);    return true;}Scene *MenuScene::scene(){    Scene *scene = Scene::create();        MenuScene *layer = MenuScene::create();        scene -> addChild(layer);        return scene;}void MenuScene::labelPressed(Ref *sender){    Director::getInstance() -> replaceScene(TransitionFade::create(1.0f, TollgateScene::scene()));}


MenuScene.h

////  MenuScene.h//  FlappyRect////  Created by Joueu on 14-10-7.////#ifndef __FlappyRect__MenuScene__#define __FlappyRect__MenuScene__#include "cocos2d.h"USING_NS_CC;class MenuScene :public Layer{public:    CREATE_FUNC(MenuScene);    virtual bool init();    static Scene *scene();private:    void labelPressed(Ref *sender);};#endif /* defined(__FlappyRect__MenuScene__) */


shareHeader.h

////  shareHeader.h//  FlappyRect////  Created by Joueu on 14-10-7.////#ifndef FlappyRect_shareHeader_h#define FlappyRect_shareHeader_h#define shareHeader_bottomHeight 170#define shareHeader_gameSceneHeight 960#define shareHeader_emptyHeight 250#define shareHeader_speed 3#define shareHeader_BirdTag 1001#define shareHeader_PipeTag 1002#endif


AppDelegate.cpp

#include "AppDelegate.h"#include "HelloWorldScene.h"#include "TollgateScene.h"#include "MenuScene.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");        director->setOpenGLView(glview);    }    glview -> setDesignResolutionSize(640, 1136, ResolutionPolicy::EXACT_FIT);    // turn on display FPS    director->setDisplayStats(true);    // 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 = HelloWorld::createScene();    auto scene = MenuScene::scene();    // 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();}
由于写得比较仓促,就没有写注释了,不要介意哈...


图片资源在这里:图片资源

1 0
原创粉丝点击