Friday, October 4, 2013

Cocos2d-x: simple button effect

One of the great things about cocos2d-x is the easy way to create and animate objects.

Here is a simple example of:

1) create a button
2) create a feedback effect when the button is pressed (manualy) and call an action when the feedback is over

1) create a button

Add these to your scene .h.
virtual void  onMenuItemSelected( CCObject* item );
CCMenuItemSprite* createMenuButton( const char* img );

CCMenuItemSprite*   btEnter;

void actionEnter();
Now implement the funtions in your .cpp. The following function helps a lot when you need to create a lot of buttons...
CCMenuItemSprite* YourScene::createMenuButton( const char* img ) {

 CCSprite* spr = CCSprite::create( img );
 if( ! spr ) {
  return NULL;
 }

 CCMenuItemSprite* item = CCMenuItemSprite::create( spr,
                   NULL, NULL, this,
                   menu_selector( YourScene::onMenuItemSelected ) );

 return item;
}
... and instantiate your button on the init of your scene:
btEnter = CCSprite::create( "btEnter.png" );
2) create a feedback effect when the button is pressed and call an action when the feedback is over

This is the feedback for all the buttons. When pressed, the btEnter will run a scale animation and than call the function actionEnter.
void YourScene::onMenuItemSelected( CCObject* item ) {

    if( item == btEnter ){
        btEnter->runAction(
                CCSequence::create(
                        CCScaleTo::create( 0.1f, 1.2f ),
                        CCScaleTo::create( 0.1f, 1.0f ),
                        CCCallFunc::create( this, 
                      callfunc_selector( YourScene::actionEnter ) ),
                        NULL ) );
    }
}
Implement the actionEnter() with some action for this button.

Run your app and now you have a button with a simple feedback effect and some specific action!

That was simple but gold! :)

See ya...
Keep playing, keep touching!

No comments:

Post a Comment