Cocos2d-x 3.0 screen touch and message distribution mechanism

Source: Internet
Author: User

Cocos2d-x 3.0 screen touch message distribution mechanism beginner

* *********************************** Please specify the source: bytes ********************************************



Digress:

Alas. School started! Annoying,

This is already a junior year,

At this time two years ago, I was an ignorant freshman or younger student,

Two years later, we are about to enter the community for employment.

Time flies, and time flies ~



Body:

I haven't done cocos2d-x for a long time, this exercise, screen touch and message distribution mechanism.

Here, I use the cocos2d-x version 3.0 to practice, the environment is vs2012 + win7


First, create a project and add an genie to the scenario.

Create a project: Cocos New-p xxx (package name)-l XXX (language)-d xxx (save path)

Select a genie, put it in the Resource Directory, and add the resource item in vs2012.



Then, create a new genie and add it to the current scenario Hello world.

Auto sprite_2 = sprite: Create ("player.png"); sprite_2-> setposition (point (visiblesize. width/2 + origin. x, visiblesize. height/2 + origin. y); // The image is slightly larger. Reduce sprite_2-> setscale (0.4f); this-> addchild (sprite_2 );

In this way, an genie has been added, and the next step is to handle the touch event.


We need to touch a location and let the genie move to that location. The steps are as follows:

-- Define the listener object of the listener event

-- Define the callback method of the listener object

-- Register on the event distributor


Because you can click a single point of touch onebyone.

First, define the listener object for the listener event:

Auto listener = eventlistenertouchonebyone: Create ();


Then, define the callback method,

The scene class in which the genie belongs is inherited from the layer class. There are touch virtual functions in the layer class,

Therefore, we only need to copy the data and overwrite it to customize the callback function.

First in the layer class, find ontouchbegan, ontouchmoved, ontouchended



Then, copy the statement to helloworldscene. h and define it in. cpp.



Make some simple definitions first, and then define the callback method in the file. We can see from the following:


Cc_callback_2 has two parameters: _ selector _ and _ target _

_ Selector _: Which function is selected for callback? -- It is obviously the corresponding function in the current class.

_ Target _: Which object is triggered? -- Is the current scenario

Therefore, it should be:

// Define the listener object callback method listener-> ontouchbegan = cc_callback_2 (helloworld: ontouchbegan, this); listener-> ontouchmoved = cc_callback_2 (helloworld: ontouchmoved, this ); listener-> ontouchended = cc_callback_2 (helloworld: ontouchended, this );

(PS: cc_callback_2 for Xiami?

Click to enter its definition. You can see:

// new callbacks based on C++11#define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__)#define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__)#define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__)#define CC_CALLBACK_3(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)

Cc_callback _ .. this operation is actually performed using STD: bind.

In other words, an object is bound to a method.

It should be noted that the number of parameters below does not represent several parameters, but several placeholders.

For more details, see the story that STD: bind and cc_callback have to say)


* Here It also shows a small difference between cocos2d-x 2. x and 3. X:

In 2.x, You need to register an event listener.

In 3.x, You need to define a listener object, define the callback method, and finally bind the listener to the event distributor.


Now add the following to the event DISPATCHER:

_ Eventdispatcher

Register a listener, which includes the following types:









We use the last type, which is based on the scenario map priority.

// Register _ eventdispatcher-> addeventlistenerwithscenegraphpriority (listener, this) in the event distributor );

Two parameters: the first parameter indicates the listening object and the second parameter indicates the node on which the listening object is located.


After talking about this, let's give it a try. So far, is it correct,

This is to check whether our click actions can be obtained and distributed.


In helloworld: ontouchbegan, set the coordinates of the clicked output on the console:

bool HelloWorld::onTouchBegan(Touch *touch, Event *unused_event){log("the location is: %lf,%lf !",touch->getLocationInView().x,touch->getLocationInView().y);return true;}

Log is the printing function,

% Lf, the output coordinate is double type,

Getlocation is used to obtain the OpenGL coordinate system (in the lower left corner)

Getlocationinview is used to obtain the current screen coordinate system (in the upper left corner)


OK, get it done, run it!

An error occurred!



Copy ontouchbegan from the layer without adding a namespace to them,

You can directly add a sentence in helloworldscene. h:

Using namespace cocos2d;

Or using_ns_cc;

Or, you can add cocos2d before the corresponding touch and event ::

 bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event);  void onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *unused_event);  void onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *unused_event); 

Okay. Run it now ~



Well, click the mouse to output the corresponding coordinates.


We can continue!

Our goal is to click the screen and let the designated genie move to this position.

Now we can get the position of the click screen. How can we move the specified genie to this position?

To specify the genie, you need to use the tag to mark the genie, settag

Sprite_2-> settag (33 );

I defined a number 33 for it (of course, set it as needed .)


The number is set. Now, let the user touch this point and get this genie to facilitate subsequent operations.

Bool helloworld: ontouchbegan (touch * touch, event * unused_event) {log ("the location is: % lf, % lf! ", Touch-> getlocationinview (). x, touch-> getlocationinview (). y); // create a new genie and get the sprite auto sprite = This-> getchildbytag (33); sprite-> setposition (point (touch-> getlocation () by serial number (). x, touch-> getlocation (). y); Return true ;}

Now, we can click a point where the center of our genie will be located,

Next, you can do some actions. Do not immediately show up and let it move.


This can be solved through moveTo in the previously learned runaction:

Bool helloworld: ontouchbegan (touch * touch, event * unused_event) {log ("the location is: % lf, % lf! ", Touch-> getlocationinview (). x, touch-> getlocationinview (). y); // create a new genie and get the genie auto sprite = This-> getchildbytag (33) by serial number ); // sprite-> setposition (point (touch-> getlocation (). x, touch-> getlocation (). y); sprite-> runaction (moveTo: Create (0.5, point (touch-> getlocation (). x, touch-> getlocation (). y); Return true ;}

Finished ,~ (* ^__ ^ *)~


Now, it's more difficult. How can we drag it?

In fact, it is not difficult to get this genie and setposition in ontouchmoved. Of course, the ontouchbegan should be deleted before.

void HelloWorld::onTouchMoved(Touch *touch, Event *unused_event){auto sprite=this->getChildByTag(33);sprite->setPosition(Point(touch->getLocation().x,touch->getLocation().y));}

OK. Run it and have a try!



Well, this is now.

In this case, you can click the screen to move the role to this position, which can be displayed directly, moved, or dragged.

The procedure is as follows:

1. Create an operating genie in the scenario

2. Create a listener object for the listener event

3. Define the object callback function

4. Register in the event distributor

5. Change the content in ontouchbegan and ontouchmoved to achieve the goal.


.. End ..




* *********************************** Please specify the source: bytes ********************************************

Cocos2d-x 3.0 screen touch and message distribution mechanism

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.