cocos2d-x 之 CCCallFunc CCCallFuncN CCCallFuncND

#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"

using namespace cocos2d;
using namespace CocosDenshion;

CCScene* HelloWorld::scene()
{
    CCScene *scene = CCScene::create();
    HelloWorld *layer = HelloWorld::create();
    scene->addChild(layer);
    return scene;
}
bool HelloWorld::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }
    CCSize size = CCDirector::sharedDirector()->getWinSize();

    //CCCallFunc 调用的方法不包含参
    CCSprite* callFuncSp = CCSprite::create("Icon.png");
    callFuncSp->setPosition(ccp(size.width/4, size.height*0.5));
    this->addChild(callFuncSp);
    callFuncSp->runAction(CCCallFunc::create(this, callfunc_selector(HelloWorld::callback1)));
    
    //CCCallFuncN 调用的方法包含一个CCNode*类型的参数,表示执行动作的对象。
    CCSprite* callFuncNSp = CCSprite::create("Icon.png");
    callFuncNSp->setPosition(ccp(size.width/2, size.height*0.5));
    this->addChild(callFuncNSp);
    callFuncNSp->runAction(CCCallFuncN::create(this, callfuncN_selector(HelloWorld::callback2)));
    
    //CCCallFuncND,回调,ND表示CCNode和Data,可以传递对象本身和一个void*类型参数,void*表示可以是任意类型的参数
    CCLabelTTF* title = CCLabelTTF::create("void* 要传的参数", "Marker Felt", 16); //自定义一个CCLabelTTF
    title->setPosition(ccp(size.width/4*3, size.height*0.6));
    this->addChild(title);
    
    CCSprite* callFuncNDSp = CCSprite::create("Icon.png");
    callFuncNDSp->setPosition(ccp(size.width/4*3, size.height*0.5));
    this->addChild(callFuncNDSp);
    callFuncNDSp->runAction(CCCallFuncND::create(this, callfuncND_selector(HelloWorld::callback3), (void*)title));
    

    return true;
}

void HelloWorld::callback1()
{
    CCSize s = CCDirector::sharedDirector()->getWinSize();
    CCLabelTTF *label = CCLabelTTF::create("callback 1 called", "Marker Felt", 16);
    label->setPosition(ccp( s.width/4*1,s.height/3));
    addChild(label);
}

//CCNode* sender为运行动作的它本身也就是CCSprite* callFuncNSp
void HelloWorld::callback2(CCNode* sender)
{
    CCSize s = CCDirector::sharedDirector()->getWinSize();
    CCLabelTTF *label = CCLabelTTF::create("callback 2 called", "Marker Felt", 16);
    label->setPosition(ccp( s.width/4*2,s.height/3));
    addChild(label);
    
    //自身做顺时针旋转动作
    sender->runAction(CCRepeatForever::create(CCRotateBy::create(1, 360)));
}

//CCNode* sender也就是CCSprite* callFuncNDSp. void的字面意思是“无类型”,void*则为“无类型指针”,void*可以指向任何类型的数据。
void HelloWorld::callback3(CCNode* sender, void* data)
{
    CCSize s = CCDirector::sharedDirector()->getWinSize();
    CCLabelTTF *label = CCLabelTTF::create("callback 3 called", "Marker Felt", 16);
    label->setPosition(ccp( s.width/4*3,s.height/3));
    addChild(label);
    
    //自身做逆时针旋转动作
    sender->runAction(CCRepeatForever::create(CCRotateBy::create(1, -360)));
    
    //void* data也就是CCLabelTTF* title
    CCLabelTTF* title = (CCLabelTTF*)data;
    title->runAction(CCRepeatForever::create(CCJumpBy::create(1, ccp(0, 0), 30, 2)));
}

效果图:


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