Cocos2d-x Study Notes-touch screen event details

Source: Internet
Author: User

The biggest difference between a game and a video is interaction. Players can control the roles in the game. Currently, mobile devices are almost one mobile device, basically all of which are based on touch screens, today I will learn how cocos2d-x is to achieve the touch screen operation processing.
1. First, let's take a look at several related categories and the operation and execution processes when handling touch screen events.
CCTouch: it encapsulates touch points and can return a CCPoint through the locationInView function.
CCTouchDelegate: it is a touch event Delegate, that is, the system captures a touch event and submits it to it or its subclass for processing. Therefore, when processing a touch event, we must inherit it. It encapsulates the following functions for processing touch screen events:
[Cpp]
Virtual void ccTouchesBegan (CCSet * pTouches, CCEvent * pEvent );
Virtual void ccTouchesMoved (CCSet * pTouches, CCEvent * pEvent );
Virtual void ccTouchesEnded (CCSet * pTouches, CCEvent * pEvent );
Virtual void ccTouchesCancelled (CCSet * pTouches, CCEvent * pEvent );

Virtual bool ccTouchBegan (CCTouch * pTouch, CCEvent * pEvent );
Virtual void ccTouchMoved (CCTouch * pTouch, CCEvent * pEvent );
Virtual void ccTouchEnded (CCTouch * pTouch, CCEvent * pEvent );
Virtual void ccTouchCancelled (CCTouch * pTouch, CCEvent * pEvent );
The ccTouchesCancelled and ccTouchCancelled functions are rarely used. This method is called only when the system interrupt notification is received and the touch event needs to be canceled. For example, the application does not respond for a long time, the current view is removed from the window, and the phone number is reached when it is touched.

CCTargetedTouchDelegate and CCStandardTouchDelegate are subclasses of CCTouchDelegate. The class structure is as follows:

CCStandardTouchDelegate is used to process multi-point touch; CCTargetedTouchDelegate is used to process single-point touch.

CCTouchDispatcher: Implements touch event distribution. It encapsulates the following two functions to add CCStandardTouchDelegate and CCTargetedTouchDelegate to the distribution list:

[Cpp] view plaincopy
Void addStandardDelegate (CCTouchDelegate * pDelegate, int nPriority );
Void addTargetedDelegate (CCTouchDelegate * pDelegate, int nPriority, bool bSwallowsTouches );
CCTouchHandler: encapsulates the priority of CCTouchDelegate and its corresponding priority. The higher the priority, the easier it is to obtain the event processing permission during distribution. CCStandardTouchHandler and CCTargetedTouchHandler are its subclasses.

The following describes how to process and execute touch screen events:
The user-defined class inherits CCTouchDelegate, overwrites the touch-screen event handler function and registerWithTouchDispatcher function, and calls the registerWithTouchDispatcher function in the init or onEnter function, for example:

[Cpp]
Void GameLayer: registerWithTouchDispatcher ()
{
Cocos2d: CCTouchDispatcher: sharedDispatcher ()-> addTargetedDelegate (this, 0, true );
}
Add the CCTouchDelegate to the CCTouchDispatcher distribution list. The addTargetedDelegate function will create the CCTouchHandler object corresponding to CCTouchDelegate and add it to CCMutableArraym_pTargetedHandlers. See the source code:
[Cpp
Void CCTouchDispatcher: addTargetedDelegate (CCTouchDelegate * pDelegate, int nPriority, bool bSwallowsTouches)
{
CCTouchHandler * pHandler = CCTargetedTouchHandler: handlerWithDelegate (pDelegate, nPriority, bSwallowsTouches );
If (! M_bLocked)
{
ForceAddHandler (pHandler, m_pTargetedHandlers );
}
Else
{
/**....*/
}
}

Void CCTouchDispatcher: forceAddHandler (CCTouchHandler * pHandler, CCMutableArray * pArray)
{
Unsigned int u = 0;

CCMutableArray: CCMutableArrayIterator iter;
For (iter = pArray-> begin (); iter! = PArray-> end (); ++ iter)
{
CCTouchHandler * h = * iter;
If (h)
{
If (h-> getPriority () <pHandler-> getPriority ())
{
++ U;
}

If (h-> getDelegate () = pHandler-> getDelegate ())
{
CCAssert (0 ,"");
Return;
}
}
}

PArray-> insertObjectAtIndex (pHandler, u );
}

When an event is distributed, the CCXXXTouchHandler is extracted from the handler, and then the delegate's: pHandler-> getDelegate ()-> ccTouchBegan (pTouch, pEvent); function is implemented by the touches function of cctouchdispat, considering the length issue, we will not post the specific code. This function first processes targeted and then standard, so CCTargetedTouchDelegate has a higher priority than CCStandardTouchDelegate. When will the touches function be triggered? CCTouchDispatcher inherits the EGLTouchDelegate class and the EGLTouchDelegate class source code:
[Cpp]
Class CC_DLL EGLTouchDelegate
{
Public:
Virtual void touchesBegan (CCSet * touches, CCEvent * pEvent) = 0;
Virtual void touchesMoved (CCSet * touches, CCEvent * pEvent) = 0;
Virtual void touchesEnded (CCSet * touches, CCEvent * pEvent) = 0;
Virtual void touchesCancelled (CCSet * touches, CCEvent * pEvent) = 0;

Virtual ~ EGLTouchDelegate (){}
};

CCTouchDispatcher implements these four functions, which call the touches function:
[Cpp]
Void CCTouchDispatcher: touchesBegan (CCSet * touches, CCEvent * pEvent)
{
If (m_bDispatchEvents)
{
This-> touches (touches, pEvent, CCTOUCHBEGAN );
}
}
/** The other three methods are similar **/

These touch screen processing functions are called at the underlying layer of a specific platform. This Code is available in AppDelegate. cpp:
[Cpp]
CCDirector * pDirector = CCDirector: shareddire ();
PDirector-> setOpenGLView (& CCEGLView: Export dopenglview ());

Continue to follow up the setOpenGLView function and find this Code:
[Cpp]
CCTouchDispatcher * pTouchDispatcher = CCTouchDispatcher: sharedDispatcher ();
M_pobOpenGLView-> setTouchDelegate (pTouchDispatcher );
PTouchDispatcher-> setDispatchEvents (true );

Call the setTouchDelegate function in the CCEGLView class of a specific platform. Because I am on windows, CCEGLView corresponds to the CCEGLView class of the CCEGLView_win32.h file. The corresponding setTouchDelegate function is:
[Cpp]
Void setTouchDelegate (EGLTouchDelegate * pDelegate );

The system uses the WindowProc function of the CCEGLView class to process the DOWN, MOVE, and UP events of the mouse in the Windows window, and calls the touchesBegan, touchesMoved, and touchesEnded functions through pDelegate.
[Cpp]
LRESULT CCEGLView: WindowProc (UINT message, WPARAM wParam, LPARAM lParam)
{
Switch (message)
{
Case WM_LBUTTONDOWN:
If (m_pDelegate & m_pTouch & MK_LBUTTON = wParam)
{
POINT pt = {(short) LOWORD (lParam), (short) HIWORD (lParam )};
If (PtInRect (& m_rcViewPort, pt ))
{
M_bCaptured = true;
SetCapture (m_hWnd );
M_pTouch-> SetTouchInfo (0, (float) (pt. x-m_rcViewPort.left)/m_fScreenScaleFactor,
(Float) (pt. y-m_rcViewPort.top)/m_fScreenScaleFactor );
M_pSet-> addObject (m_pTouch );
M_pDelegate-> touchesBegan (m_pSet, NULL );
}
}
Break;

Case WM_MOUSEMOVE:
If (MK_LBUTTON = wParam & m_bCaptured)
{
M_pTouch-> SetTouchInfo (0, (float) (short) LOWORD (lParam)-m_rcViewPort.left)/m_fScreenScaleFactor,
(Float) (short) HIWORD (lParam)-m_rcViewPort.top)/m_fScreenScaleFactor );
M_pDelegate-> touchesMoved (m_pSet, NULL );
}
Break;

Case WM_LBUTTONUP:
If (m_bCaptured)
{
M_pTouch-> SetTouchInfo (0, (float) (short) LOWORD (lParam)-m_rcViewPort.left)/m_fScreenScaleFactor,
(Float) (short) HIWORD (lParam)-m_rcViewPort.top)/m_fScreenScaleFactor );
M_pDelegate-> touchesEnded (m_pSet, NULL );
M_pSet-> removeObject (m_pTouch );
ReleaseCapture ();
M_bCaptured = false;
}
Break;
/**....*/
}
}

OK. Now we should understand the execution process of functions related to touch screen operations. It should be similar on other platforms.

2. Implement touch screen event processing
After understanding the principle, it is easy to implement: Define a CCTouchDelegate (or its subclass CCTargetedTouchDelegate/CCStandardTouchDelegate), and then rewrite the processing functions (began, move, end ), add the defined CCTouchDelegate to the distribution list and delete it from the distribution list in the onExit function.
In normal development, there are two methods: (1) inherit CCLayer and process touch screen functions in the layer. (2) inherit CCSprite and CCTouchDelegate (or its subclass ).
The above two methods are the same in principle.
1. The following describes how to handle touch screen events by inheriting CCLayer.
(1) CCStandardTouchDelegate
Adding CCStandardTouchDelegate is very simple. You only need to rewrite the touch screen processing function and call setIsTouchEnabled (true ). The main code is as follows:

[Cpp]
// In the init Function
This-> setIsTouchEnabled (true );

Void GameLayer: ccTouchesBegan (CCSet * pTouches, CCEvent * pEvent)
{
CCSetIterator it = pTouches-> begin ();
CCTouch * touch = (CCTouch *) (* it );
CCpoint touchLocation = touch-> locationInView (touch-> view ());
TouchLocation = CCDirector: sharedDirector ()-> convertToGL (m_tBeginPos );
/**....**/
}
Why didn't we add CCStandardTouchDelegate to the distribution list and delete it from the distribution list? Because the setIsTouchEnabled function has already helped us. See the source code:
[Cpp]
Void CCLayer: setIsTouchEnabled (bool enabled)
{
If (m_bIsTouchEnabled! = Enabled)
{
M_bIsTouchEnabled = enabled;
If (m_bIsRunning)
{
If (enabled)
{
This-> registerWithTouchDispatcher ();
}
Else
{
// Have problems?
CCTouchDispatcher: sharedDispatcher ()-> removeDelegate (this );
}
}
}
}

Void CCLayer: registerWithTouchDispatcher ()
{
/**....**/
CCTouchDispatcher: sharedDispatcher ()-> addStandardDelegate (this, 0 );
}

Void CCLayer: onExit ()
{
If (m_bIsTouchEnabled)
{
CCTouchDispatcher: sharedDispatcher ()-> removeDelegate (this );
UnregisterScriptTouchHandler ();
}

CCNode: onExit ();
}

(2) CCTargetedTouchDelegate
Look directly at the CCMenu (menu) Class in the cocos2d-x, which inherits CCLayer. Some source code is as follows:
[Cpp]
Class CC_DLL CCMenu: public CCLayer, public CCRGBAProtocol
{
/**....*/
Virtual void registerWithTouchDispatcher ();

/**
@ Brief For phone event handle functions
*/
Virtual bool ccTouchBegan (CCTouch * touch, CCEvent * event );
Virtual void ccTouchEnded (CCTouch * touch, CCEvent * event );
Virtual void ccTouchCancelled (CCTouch * touch, CCEvent * event );
Virtual void ccTouchMoved (CCTouch * touch, CCEvent * event );

/**
@ Since v0.99.5
Override onExit
*/
Virtual void onExit ();

/**....*/
};
}

// Menu-Events, called in onEnter of CCLayer
Void CCMenu: registerWithTouchDispatcher ()
{
CCTouchDispatcher: sharedDispatcher ()-> addTargetedDelegate (this, kCCMenuTouchPriority, true );
}

Bool CCMenu: ccTouchBegan (CCTouch * touch, CCEvent * event)
{
/**....*/
}

Void CCMenu: onExit ()
{
/**....*/
CCLayer: onExit ();
}

2. The following method inherits CCSprite
Define a Ball class that inherits CCSprite and CCTargetedTouchDelegate. The source code is as follows:
[Cpp]
Class Ball: public CCSprite, public CCTargetedTouchDelegate
{
Public:
Ball (void );
Virtual ~ Ball (void );

Virtual void onEnter ();
Virtual void onExit ();

Virtual bool ccTouchBegan (CCTouch * touch, CCEvent * event );
Virtual void ccTouchMoved (CCTouch * touch, CCEvent * event );
Virtual void ccTouchEnded (CCTouch * touch, CCEvent * event );
/**....*/

};

Void Ball: onEnter ()
{
CCTouchDispatcher: sharedDispatcher ()-> addTargetedDelegate (this, 0, true );
CCSprite: onEnter ();
}

Void Ball: onExit ()
{
CCTouchDispatcher: sharedDispatcher ()-> removeDelegate (this );
CCSprite: onExit ();
}

Bool Ball: ccTouchBegan (CCTouch * touch, CCEvent * event)
{
CCPoint touchPoint = touch-> locationInView (touch-> view ());
TouchPoint = CCDirector: sharedDirector ()-> convertToGL (touchPoint );
/**....*/
Return true;
}

Note: The returned values of virtual bool ccTouchBegan (CCTouch * pTouch, CCEvent * pEvent) have an impact on the touch screen message.
If false is returned, the ccTouchMoved (), ccTouchEnded (), and ccTouchCanceld () methods are not processed, but are processed by the object that receives the touch screen message. If true is returned, it indicates that the ccTouchMoved (), ccTouchEnded (), and ccTouchCanceld () methods will be processed, and the touch screen message will be consumed. The objects that need to receive the touch screen message will not receive the touch screen message.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.