Cocos2dx -- learning notes using UIButton to create virtual buttons
Today, we continue to improve our small DEMO. We need to add some virtual buttons. First, we need to move the buttons up and down.
Here we need to implement the effect of pressing continue and releasing it.
I tried to use CCMenuImage. Unfortunately, CCMenuImage only supports event processing after being pressed and then popped up. There is no way to control the time between the press and the lift.
UIButton can meet this requirement.
UIButton is the UI control class in cocos2dx extension, derived from the Widget.
Similar to CCMenuImage, each UI control must be placed in a UILayer. That is to say, UILayer is the container of the UI control.
The creation process is similar to the following:
Button *m_pUpBtn = Button::create();m_pUpBtn->setTouchEnabled( true );m_pUpBtn->loadTextures( "DirKeyNor.png", "DirKeySel.png", "" );m_pUpBtn->setPosition( ccp( 180.0f, 160.0f + m_pUpBtn->getContentSize().height/2 ) );m_pUpBtn->addTouchEventListener( this, toucheventselector( DirPanel::OnDirUp ) );uiLayer->addWidget( m_pUpBtn );
By the way, the UIButton class does not exist.
typedef cocos2d::ui::Button UIButton;
In fact, it is derived from typedef, and the real control class is Button.
With the Button, we only need to create four Button controls and add them to UILayer. Of course, UILayer may need to be added to the node. Then add a touch RESPONSE event for each button.
The format is similar to this:
void DirPanel::OnDirUp( cocos2d::CCObject *obj, cocos2d::ui::TouchEventType type ){switch ( type ){case TOUCH_EVENT_BEGAN:{m_pHero->setDir( DIR_UP );}break;case TOUCH_EVENT_ENDED:{m_pHero->setDir( DIR_NONE );}break;}}
With the above, the virtual buttons are captured. Of course, in order to cooperate with the virtual buttons, the corresponding control character movement interface is required.
So far, the virtual buttons have fallen.