cocos2d-x 分享某类的静态实例方法与调用

获取当前某类的静态实例方法:如下代码,举例类名为:  PlayScene

在 .h 文件中声明:

class PlayScene : public CCLayer

{

public:

    //获取当前PlayScene的静态实例(分享)

    static PlayScene* sharedPlay();

    static CCScene* createPlayScene();

    virtual bool init();

    CREATE_FUNC(PlayScene);



};

在 .cpp 文件中定义:

#include "PlayScene.h"

static PlayScene* ps;



PlayScene* PlayScene::sharedPlay()

{

    if(ps)

    {

        return ps;

    }

    return NULL;

}



CCScene* PlayScene::createPlayScene()

{

    CCScene* scene = CCScene::create();

    PlayScene* layer = PlayScene::create();

    scene->addChild(layer);

    return scene;

}



bool PlayScene::init()

{

    if(!CCLayer::init())

    {

        return false;

    }

    ps = this;

}

调用举例:

    //游戏主角子弹与怪物的碰撞检测,当发生碰撞时当从游戏中去除相碰撞的子弹与怪物

    //getEemyArray()为定义在PlayScene类中得到怪物数组的函数,

    for(int i = 0; i < PlayScene::sharedPlay()->getEnemyArray()->count(); i ++)

    {

        Enemy* enemy = (Enemy*) PlayScene::sharedPlay()->getEnemyArray()->objectAtIndex(i);

        if(this->boundingBox().intersectsRect(enemy->boundingBox()))

        {

            PlayScene::sharedPlay()->getEnemyArray()->removeObject(enemy); //从怪物数组中去除对象

            PlayScene::sharedPlay()->removeChild(enemy, true); //从游戏的当前层上去除相撞怪物

            PlayScene::sharedPlay()->removeChild(this, true); //从游戏当前层上去除相撞子弹

        }

    }

 

你可能感兴趣的:(cocos2d-x)