Cocos2d-x中在一个CClayer上设置按钮控制另一个CClayer上的对象



Hi,推荐文件给你 "碰撞检测例子.zip" http://vdisk.weibo.com/s/J6Ld-


新建一个工程,之后再一个类HudLayer


HudLayer.h

#include "cocos2d.h"
USING_NS_CC;
class HudLayer:public CCLayer
{
public:
    CREATE_FUNC(HudLayer);
    bool init();
    
    //调用的方法
    void start();
};


HudLayer.cpp

bool HudLayer::init()
{
    bool pRet = false;
    do {
        CC_BREAK_IF(!CCLayer::init());
        //设置一个按钮
        CCMenuItemImage* start = CCMenuItemImage::create("Icon-72.png", "Icon-72.png", this, menu_selector(HudLayer::start));
        start->setPosition(ccp(100, 100));
        CCMenu* pMenu = CCMenu::create(start,NULL);
        this->addChild(pMenu);
        pRet = true;
    } while (0);
    return pRet;
}

void HudLayer::start()
{
    //发送一条消息调用相应的方法
    CCNotificationCenter::sharedNotificationCenter()->postNotification("change");
}


接下来,我们要对HelloWorldScene.h做如下修改

#include "HudLayer.h"
USING_NS_CC;
class HelloWorld : public cocos2d::CCLayerColor
{
public:
    // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)
    virtual bool init();

    // there's no 'id' in cpp, so we recommend to return the class instance pointer
    static cocos2d::CCScene* scene();
    HelloWorld();
    CCArray* _arr;
    HudLayer* hud;
    void change();
    // preprocessor macro for "static create()" constructor ( node() deprecated )
    CREATE_FUNC(HelloWorld);
};

 //注册一条消息,在HudLayer类中发送的消息
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::change), "change", NULL);
    
    CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    cache->addSpriteFramesWithFile("zzzz.plist");
    
    CCSpriteBatchNode* node = CCSpriteBatchNode::create("zzzz.pvr.ccz");
    this->addChild(node);
    
                                                            
    _arr = CCArray::create();
    _arr->retain();
    CCSprite* player = CCSprite::createWithSpriteFrameName("Player.png");
    player->setPosition(ccp(100, 100));
    node->addChild(player);
    _arr->addObject(player);
    hud = HudLayer::create();
    this->addChild(hud);
    
    return true;
}
void HelloWorld::change()
{
    CCSprite* player1 = (CCSprite*)_arr->objectAtIndex(0);
    CCMoveBy* moBy = CCMoveBy::create(1, ccp(0, 100));
    player1->runAction(moBy);
}



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