Zhiyi game development tutorial cocos2d-x transplant version 004

Source: Internet
Author: User
    • Ccstandardtouchdelegate
    • Cctargetedtouchdelegate

We know that cocos2d-x is a C ++ porting version of The cocos2d-iphone project, which has cross-platform features. At the same time cocos2d-x and cocos2d-iphone to maintain a high degree of synchronization, which fundamentally limits it is a mobile phone, tablet and other devices tailored to the game engine. The support for Win32 and other platforms is only for convenient development and debugging.
If you are preparing to develop a PC game, you are right to use the engine specifically designed for PC. Although such a sentence appeared in an article about cocos2d-x, but I think some things are still clear, no one's time should be wasted.

If you are adding PC-side development to cocos2d-x like me, there are a lot of concepts to note.
For example, the mouse that we often use on a PC turns into a finger on a cell phone or tablet. Of course, this is not only a media change, but also a change in usage habits.

The disappearing mouse goes through the status
As we all know, a button on a PC usually contains four states: Normal, mouse passing, mouse pressing, and disabling, while on the mobile phone and panel, A button usually has only three States: Normal, pressed, and disabled.
This is easy to understand.
First, no matter where the mouse is placed, it will not be able to break away from the display screen after all, and it is much more difficult to let a person put his finger on the touch screen at all times.
Second, the mouse has buttons, but the human hand has no buttons. It is difficult to move the mouse away from the click.
Therefore, on mobile phones and tablets, the mouse passing through the traditional meaning is almost nonexistent.

Magical multi-touch
For mobile phone and tablet users, multi-point touch screens are common. Although PCS also have peripherals that support multi-point input, software that supports this feature is not common. For those who are familiar with PC, it is easier to accept single point of mouse input.

The so-called habit is just getting used to it. It takes a long time, that is, the thing. Today, let's get to know this touch ).

Cocos2d-x touch event processing

In cocos2d-x, touch is an important means of interaction. Although we did not explicitly state this touch event before, we did not leave it for a moment. The trigger of each menu is actually a touch.


To be precise, we have a relationship with touch. In article 1, we have implemented the function of moving the ship after clicking the screen.

 1   Void Gamelayer: cctouchesended (ccset * ptouches, ccevent * pevent)
2 {
3 Cctouch * Touch = (cctouch *) ptouches-> anyobject ();
4 // Obtain touch point coordinates
5 Ccpoint location = touch-> locationinview (touch-> View ());
6 Ccpoint convertedlocation = ccdirector: shareddirector ()-> converttogl (location );
7 // Let the ship move in 1 second
8 Flight-> runaction (ccmoveto: actionwithduration ( 1.0f , CCP (convertedlocation. X, convertedlocation. y )));
9 }

HoweverCodeTo take effect, you must also enable the touch event in initialization.

1 BoolGamelayer: Init (Void)
4//Accept touch now!
5Setistouchenabled (True);

Follow in to see how to enable touch events.

 1   Void Cclayer: setistouchenabled ( Bool Enabled)
2 {
3 If (M_bistouchenabled! = Enabled)
4 {
5 M_bistouchenabled = enabled;
6 If (M_bisrunning)
7 {
8 If (Enabled)
9 {
10 This -> Registerwithtouchdispatcher ();
11 }
12 Else
13 {
14 // Have problems?
15 Cctouchdispatcher: shareddispatcher ()-> removedelegate ( This );
16 }
17 }
18 }
19 }
21 Void Cclayer: registerwithtouchdispatcher ()
22 {
23 Cctouchdispatcher: shareddispatcher ()-> addstandarddelegate ( This , 0 );
24 }

The above Code adds a standard proxy through cctouchdispatcher to enable the touch function.

The standard proxy means that you can receive all the messages-began, moved, ended, and cancelled ). The information of the touch point is represented by ccset.

High flexibility is the same as high permissions, and the cost of high flexibility is that you have to write additional code on your own.

The flexibility is too high. Instead, I don't know where to start. I just don't want to talk about it. I will talk about it later when I need it. But one thing to mention is that the standard proxy type is basically the same as Apple's cocoatouch framework, so most of cococoatouch's solutions are also feasible in cocos2d-x.


Compared with the standard proxy, the target proxy features are naturally weaker, but it is much easier to use.

There are two significant benefits to using the target Proxy:
1. You don't have to deal with ccset, schedulingProgramSplit it for you, and you will get a single touch event each time you use it.
2. You can "claim" a touch event by making cctouchbegan return true. A "claimed" Touch event is only distributed to the proxy object of the "claimed" event. In this way, you can be freed from the multi-touch detection of the bitter sea.

Let's conduct a practical drill. Suppose we have received a task that requires an genie to be displayed on the screen, which is a sequential Frame Animation for loop playback. We can drag it when we press it on the Genie. If it is outside the genie, it cannot be dragged.

First, analyze the tasks we receive. There is no difficulty in displaying a sequence Frame Animation genie For Loop playback. We have done this many times before. You can drag it when you press it on the Genie. You cannot drag it when you press it on the outside. If you use a standard proxy object, you must add a large number of judgments and States, obviously, we should give priority to the target proxy.

Therefore, we need an genie that meets the target proxy, so this is a multi-inheritance class, which has two parent classes-ccsprite and cctargetedtouchdelegate.

1 ClassKillinglight:PublicCcsprite,PublicCctargetedtouchdelegate
3 Public:
4Killinglight (Void);
5Virtual~ Killinglight (Void);

To receive a touch event, you must first register it. If you no longer need it, you must perform a reverse registration. We rewrite the onenter and onexit functions of ccnode to complete registration and anti-Registration of touch events.

 1   Void Killinglight: onenter (Void )
2 {
3 Ccsprite: onenter ();
4 // We want to exclusive the "claimed" Touch event, so 3rd parameters are passed in true
5 Cctouchdispatcher: shareddispatcher ()-> addtargeteddelegate ( This , 0 , True );
6 }
8 Void Killinglight: onexit ( Void )
9 {
10 Cctouchdispatcher: shareddispatcher ()-> removedelegate ( This );
11 Ccsprite: onexit ();
12 }

Only the "claim" Touch event can be used in the target proxy object. Therefore, we need to rewrite the cctouchbegan function of cctargetedtouchdelegate.

Because the task must be dragged only when it is placed on the sprite, we need to add a judgment to determine whether the touch point is on the sprite.

1 Ccrect killinglight: rect ( Void )
2 {
3 // The following comparison is based on the anchor.
4 Const Ccsize & s = gettexturerect (). size;
5 Const Ccpoint & P = This -> Getanchorpointinpixels ();
6 Return Ccrectmake (-p. x,-P. Y, S. Width, S. Height );
7 }
9 Bool Killinglight: containstouchlocation (cctouch * Touch)
10 {
11 Return Ccrect: ccrectcontainspoint (rect (), converttouchtonodespacear (touch ));
12 }
14 Bool Killinglight: cctouchbegan (cctouch * ptouch, ccevent * pevent)
15 {
16 If (! Containstouchlocation (ptouch ))
17 Return False ;
19 Return True ;
20 }

Next, we will rewrite the cctouchmoved function of cctargetedtouchdelegate to implement the drag function.

1 VoidKillinglight: cctouchmoved (cctouch * ptouch, ccevent * pevent)
3Ccpoint touchpoint = ptouch-> locationinview (ptouch-> View ());
4Touchpoint = ccdirector: shareddirector ()-> converttogl (touchpoint );
5Setposition (touchpoint );

For ease of use, we add a static member function killinglightwithbatchnode to create a killinglight object.

 1 Killinglight * killinglight: killinglightwithbatchnode (cocos2d: ccspritebatchnode * batchnode, Const Cocos2d: ccrect & rect)
2 {
3 Killinglight * pobsprite = New Killinglight ();
4 If (Pobsprite & pobsprite-> initwithbatchnode (batchnode, rect ))
5 {
6 Pobsprite-> autorelease ();
7 Return Pobsprite;
8 }
9 Cc_safe_delete (pobsprite );
10 Return NULL;
11 }

In this way, a wizard class that supports clicking and dragging is complete, and you can use it like using ccsprite.

If you want to make this class more perfect, for example, to only respond to the first pay-as-you-go touch event so as not to grab more than one Genie, you can refer to the paddle class in touchestest.

Download Code:

When processing touch events, you must note the coordinates of coordinates. This involves many layers, including the screen coordinate system or GL coordinate system, the world coordinate system, the local coordinate system, and the point relative to which the coordinates are calculated.

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.