When developing some cocos2d projects with more complex window layers, you will find some bugs caused by no window layers. These bugs make some people who come from the Windows platform feel helpless. For example, we have a list control, in which we place some menus. When we slide the list control to make the menu option (called a) slide out of the visible range of the list control, we cannot click a again because it scrolls out of the visible range of the parent control and is not visible to the user. But cocos2d can be clicked by default, because cocos2d Message Management uses a priority message mechanism. cocos2d will send messages to cocos2d as long as the control registers and receives messages. So in cocos2d's view, the situation we just talked about is that cocos2d cannot be blocked Based on A and does not send messages to. Basically, there is no hierarchical window message mechanism (of course you can use other methods to help cocos2d, but I personally think it is not thorough enough ).
I want to establish a relatively complete hierarchical window message mechanism of cocos2d without changing any source code of cocos2d (if the source code is changed, I don't know if it will be difficult to upgrade later ). There are several basic ideas:
- In any scenario, we have a bottom layer (called the ancestor layer) that receives cocos2d touch messages. In addition, this layer can pass the touch message to all its child controls.
- In a scenario, except for the parent layer, all other controls do not accept any touch message. The source of the touch message is the parent control.
- Messages are transmitted from the underlying layer to the upstream layer. In each layer, nodes are arranged from high to low according to the order value (that is, if the order value is high, it indicates that the control is located in the upper-layer node of this layer) and traversed, wait until you encounter a node that is interested in the message and stop traversing the current layer to enter the next layer.
- Best compatibility with the known and unknown cocos2d control libraries.
Let's take a look at the organizational structure of the class: Let's talk about the general functions of each class:
- Bytouchdelegate does not inherit from cctouchdelegate or other classes (but the message processing function name is the same as cctouchdelegate ). It is a message propagation ambassador. All classes inherited from this class can automatically spread messages to all sub-controls. Instead of inheriting from cctouchdelegate, it is mainly out of design principles to avoid repeated base classes in multiple inheritance.
- Bylayer inherits from wmtouchdelegate and cclayer (not shown in the figure) and is responsible for transferring the message processing function to the Message Processing Function of bytouchdelegate, because the message processing function of bytouchdelegate is the same as that of cctouchdelegate, the cclayer has inherited cctouchdelegate, so if the transfer handler function is not displayed, the C ++ compiler will prompt that there are two version selection errors.
The message mechanism has two purposes:
- Let large Cocos2d-x netizens have a hierarchical window management mechanism.
- Let all the Cocos2d-x elements (I .e. various UIS) be naturally integrated into this mechanism.
The following changes are required to achieve this goal:
- Disable message registration for all subnodes. It is found through practice that, in order not to move the source code, a new bycocos: addchild function must be written to replace the original addchild function family. In this way, the project must call addchild to change it to bycocos :: addchild. In this function, messages of all subnodes are closed.
- Cocos2d-x source code to modify one.
1. comment out the ccassert statement in cctouchbegan of cclayer. This statement is only a wake-up function, in order to let the Cocos2d-x adapt to this mechanism, comment out this sentence. And change return true to return false. In this mechanism, true indicates that the layer is interested in window messages, which prevents messages from being transmitted to the sibling node.
Important:
- The message mechanism determines whether to click the window, so the window size is particularly important. The various controls of the cccontrol of the Cocos2d-x have been done. However, you must set the window size correctly for the new class you write.
The source code is as follows:
- Bytouchdelegate:
Bytouchdelegate. h
//// BYTouchDelegate.h// TableTest//// Created by jason on 12-12-25.////#ifndef __TableTest__BYTouchDelegate__#define __TableTest__BYTouchDelegate__#include "cocos2d.h"USING_NS_CC;//by message mechanism//node who want to receive by message must derive from BYTouchDelegate.//if node is layer, it need use macro( BY_MESSAGE_BRIDGE() ) to connect it to by message instead of ccTouchMessage.class BYTouchDelegate{public: BYTouchDelegate( CCNode* pOwner ) : m_pOwner( pOwner ), m_bDraging( false ) { m_pItemsClaimTouch = CCArray::createWithCapacity( CHILD_MAX ); assert( m_pItemsClaimTouch ); m_pItemsClaimTouch->retain(); m_pMenusClaimTouch = CCArray::createWithCapacity( CHILD_MAX ); assert( m_pMenusClaimTouch ); m_pMenusClaimTouch->retain(); } virtual ~BYTouchDelegate() { CC_SAFE_RELEASE_NULL( m_pItemsClaimTouch ); CC_SAFE_RELEASE_NULL( m_pMenusClaimTouch ); }protected: // default implements are used to call script callback if exist virtual bool byTouchBegan(CCTouch *pTouch, CCEvent *pEvent); virtual void byTouchMoved(CCTouch *pTouch, CCEvent *pEvent); virtual void byTouchEnded(CCTouch *pTouch, CCEvent *pEvent); virtual void byTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); //return value: //true: pParent is touched by user //false: pParent isn't touched by user. bool passMessage( CCNode* pParent, CCTouch *pTouch, CCEvent *pEvent );private: CCNode* m_pOwner; bool m_bDraging; //items claim touch message CCArray* m_pItemsClaimTouch; CCArray* m_pMenusClaimTouch;};#endif /* defined(__TableTest__BYTouchDelegate__) */
Bytouchdelegate. cpp
//// BYTouchDelegate.cpp// TableTest//// Created by jason on 12-12-25.////#include "BYTouchDelegate.h"#include "BYUtility.h"#pragma mark- input touchebool BYTouchDelegate::byTouchBegan(CCTouch *pTouch, CCEvent *pEvent){ //pass message to all children return passMessage( m_pOwner, pTouch, pEvent );}void BYTouchDelegate::byTouchMoved(CCTouch *pTouch, CCEvent *pEvent){ //special process for menu, we won't pass ccTouchMoved message to menu. Because we think menu doesn't need ccTouchMoved message in ios device where user always want to dray layer instead menu. The fllowing block for menu will only go once. int iNumMenus = m_pMenusClaimTouch->count(); for( int i = 0; i < iNumMenus; ++i ) { ( ( CCMenu* )m_pMenusClaimTouch->objectAtIndex( i ) )->ccTouchCancelled( pTouch, pEvent ); } if( iNumMenus > 0 ) { m_pMenusClaimTouch->removeAllObjects(); } //pass ccTouchMoved message to un-CCMenu item for( int i = 0; i < m_pItemsClaimTouch->count(); ++i ) { ( ( CCLayer* )m_pItemsClaimTouch->objectAtIndex( i ) )->ccTouchMoved( pTouch, pEvent ); }}void BYTouchDelegate::byTouchEnded(CCTouch *pTouch, CCEvent *pEvent){ //for menus for( int i = 0; i < m_pMenusClaimTouch->count(); ++i ) { ( ( CCMenu* )m_pMenusClaimTouch->objectAtIndex( i ) )->ccTouchEnded( pTouch, pEvent ); } m_pMenusClaimTouch->removeAllObjects(); //for items not menu for( int i = 0; i < m_pItemsClaimTouch->count(); ++i ) { ( ( CCLayer* )m_pItemsClaimTouch->objectAtIndex( i ) )->ccTouchEnded( pTouch, pEvent ); } m_pItemsClaimTouch->removeAllObjects();}void BYTouchDelegate::byTouchCancelled(CCTouch *pTouch, CCEvent *pEvent){ //for menus for( int i = 0; i < m_pMenusClaimTouch->count(); ++i ) { ( ( CCMenu* )m_pMenusClaimTouch->objectAtIndex( i ) )->ccTouchCancelled( pTouch, pEvent ); } m_pMenusClaimTouch->removeAllObjects(); //for items not menu for( int i = 0; i < m_pItemsClaimTouch->count(); ++i ) { ( ( CCLayer* )m_pItemsClaimTouch->objectAtIndex( i ) )->ccTouchCancelled( pTouch, pEvent ); } m_pItemsClaimTouch->removeAllObjects();}bool BYTouchDelegate::passMessage( CCNode* pParent, CCTouch *pTouch, CCEvent *pEvent ){ if( !pParent || !pParent->isVisible() ) { return false; } //if the item'size > 1, check whether use touches it. Such as TableView. //some items doesn't get size. they are medium for maintaining some children. Such as CCTableViewCell. if( pParent->getContentSize().width * pParent->getContentSize().height > 1.0f ) { CCPoint pt = pTouch->getLocation(); CCRect rcBoundingBox( 0, 0, pParent->getContentSize().width, pParent->getContentSize().height ); rcBoundingBox = CCRectApplyAffineTransform( rcBoundingBox, pParent->nodeToWorldTransform() ); if( !rcBoundingBox.containsPoint( pt ) ) { return false; } } //hande message to items CCArray* pChildren = pParent->getChildren(); //no children, but user touch this item, so return true. if( !pChildren ) { return true; } //sort all children in ascending order. pParent->sortAllChildren();CCObject* pObject = NULL;//traverse in descending order.//we only send message to the first child handling message. CCARRAY_FOREACH_REVERSE( pChildren, pObject ){//if the item claims the touch messagebool bClaim = false; CCLayer* pLayer = NULL; CCNode* pNode = NULL; pNode = ( CCNode* )pObject; assert( pNode ); //if it's layer, we should invoke its ccTouchBegan() //Make sure that you have commented the CCAssertion statement in CCLayer::ccTouchBegan(). if( ( pLayer = dynamic_cast< CCLayer* >( pNode ) ) ) { bClaim = pLayer->ccTouchBegan( pTouch, pEvent ); } //pass message for its child which doesn't derive BYTouchDelegate since child deriving BYTouchDelegate
//has pass message via ccTouchBegan().//items who doesn't derive from BYTouchDelegate can't pass touch message to its children,//so we have to help them to pass touch message.//we don't care the result of passMessage() since passMessage here is just//passing messages for the node. It doesn't mean the node is interested//in the message.passMessage( pNode, pTouch, pEvent ); //if this item is interested in this message, add it to array for other messages if( bClaim ) { //we don't use condition of &typeid( *pNode ) == &typeid( CCMenu ) since user may derive CCMenu. if ( dynamic_cast< CCMenu* >( pNode ) ) { m_pMenusClaimTouch->addObject( pNode ); } else { m_pItemsClaimTouch->addObject( pNode ); }//we only send message to the first immediate child claiming message. break; }}//if there is any item who claims the message, return true.return m_pItemsClaimTouch->count() + m_pMenusClaimTouch->count() > 0 ? true : false;}
The important points are as follows:
1. the first is m_bdragging, which is used to determine the drag function. It is mainly used for menu processing. After clicking it, the menu is interested in this message. we record the menu and pass the subsequent message, after clicking it, The touchmoved message is sent, and the menu message processing is stopped.
2. passmessage is used together with cctouchbegan to implement recursive message transmission. Passmessage also helps pass messages to its child controls without inheriting wmtouchdelegate classes (cctouchbegan of these classes does not have the message passing function.
- Bylayer. Because the main functions are completed by wmtouchdelegate, these classes only add simple functions and constraints.
Bylayer. h
//// BYLayer.h// TableTest//// Created by jason on 12-12-21.////#ifndef __TableTest__BYLayer__#define __TableTest__BYLayer__#include "cocos2d.h"#include "BYTouchDelegate.h"#include "BYMacros.h"USING_NS_CC;//BYLayer can be touched.//Every secene should have only one BYLayer to represent message center.//All children nodes shouldn't register touche message.//To achieve it, you should use BYCocos::addChild() to add child node.class BYLayer : public CCLayer, public BYTouchDelegate{ //staticpublic: CREATE_FUNC( BYLayer );//functionspublic:BYLayer() : BYTouchDelegate( this ){}bool virtual init() { setTouchEnabled( true ); return true; } BY_MESSAGE_BRIDGE(); protected:BY_TOUCH_REGISTER_TWO_MODE( 0 );};#endif /* defined(__TableTest__BYLayer__) */
It uses some macros to make it faster. But I hope it will not impede your reading. There is not much to say here. For details, please download the sample project.
PS:
- When using the project, you only need to include bycocos. h.
- Make sure that the ccassertion () Statement in the cclayer. cpp: cctouchbegan () function in the cocos2d-x is commented out and the return true is modified to return false. This is the only modification to the cocos2d-x source code by the new level window messaging mechanism.
- Note one thing in this system, because we have added a form to click to judge, so the window to join this system should be displayed, set your own form size correctly (this is often the cause of some bugs ). To shield peer nodes from receiving messages, rewrite cctouchbegan and return true.
- To add a subnode, you must use bycocos: addchild ().
- In addition, because dynamic_cast is used, some readers may worry about efficiency. However, I personally think that dynamic_cast is not c ++ garbage, and its performance impact should be very limited.
- There are many comments in the Code. If the comments are incorrect, please let me know. I am used to practicing English comments. I hope my comments do not have too many syntax errors to help you understand them. I will not talk about it here.
- Any subsequent modifications will be listed in the following revision records.
- In view of the fact that many netizens have asked me for a source code project for testing, I have passed the source code project to my network disk space for convenience.. [Http://www.xujiezhige.ys168.com]-> [Tool]-> unzip chaos.zip
1, 964kb ],
If the above link cannot be opened, please try to download the csdn resource link [Cocos2d-x level window message mechanism demo ].(Last updated)
Revision history:
- 2013-2-1, modify bytouchdelegate. cpp.
Reason for revision: it is reasonable to say that only the top child node on a layer can receive the corresponding message.
Revised content: messages are delivered to the first subnode that is interested in the message in descending order of the node zorder. Multiple subnodes overlap on one layer, all respond to message bugs.
Fixed the bug where bytouchdelegate does not accept messages when no subnode is interested in messages. This bug may occur when indirect subnodes are interested in messages. Specifically: Modify passmessage () in bytouchdelegate. cpp. The revised part starts with // Revision # began and ends with // Revision # End (# indicates the number of revisions. I wanted to mark it by color, but the color format in the csdn code box has a bug ).
- , Modify bylayer. h
Reason for revision:
1. The original version reloads onenter () and blocks messages from all subnodes. However, onenter is called during creation. If addchild () is called after creation, the added node message is not blocked, which violates the message mechanism.
2. because we have blocked subnode messages in addchild, all bylayermodal is unnecessary (because it was originally designed to shield messages by registering messages with the highest priority). If you want to shield messages in a window, make sure that the window order is the highest, and override cctouchbegan to return true. In addition, the existence of bylayerdescendant increases the complexity of the mechanism, which is more reasonable than the benefits it brings.
3. Merge bylayerancestor into bylayer to reduce the number of newly added classes and streamline the system.
Revised content: Delete the practice of blocking subnode message registration. Add the bycocos: addchild helper function, which shields messages from all subnodes.