The path of COCOS2DX learning----12th (on the Update of node nodes ' self-updating function and the use of timers)

Source: Internet
Author: User

This article is about the more important function interfaces for node nodes, the self-updating interface (update), and the timers.

OK, let's talk about the node's self-renewal.

Each of the node nodes has an update function that comes with it. And when the call to Scheduleupdate () is turned on, it is called at each frame.

We may notice that there is a setanimationinterval () method in Appdelegate, which has a Director class call. And this method is to set the frame rate of the rendering. The default is to render at 60 frames per second. Of course, not really 60 times per second, this can only be achieved at almost this rate, because the program will take time to run, especially to perform some more time-consuming methods.

So, since this is the case, if we update the function updates, then the program will call the update function at this time (1/60 seconds = 0.01666 seconds), and the time will be passed as an update parameter.

By opening the node's Update method, you can implement the update of the node's own logic code.

Okay, then let's talk about the timer, if you want to use a timer in cocos, you need to use the scheduler class, called the scheduler. This class is also sorted into node, and then provides a way for us to use it. It is possible to implement what we call a timer through its one-line class approach. I've listed one of its ways to turn on the timer, understand this, and you can understand other methods. As follows:

/****************************** Parameter 1: Callback method for Scheduler invocation * * Parameter 2: Scheduler is called once every ' interval ' second * * Parameter 3: Call (repeat+1) * * Parameter 4: The first time to start calling a lapse of ' delay ' seconds ******************************void node::schedule (sel_schedule selector, float interval, unsigned int repeat, float delay);
for the second parameter, if the time is set to 0, it will be called every frame as update, but if so, it is recommended to call its own update function using the Scheduleupdate method. For the third parameter, if you want to keep calling, you can set it by macro definition cc_repeat_forever.

OK, so let's take a look at how to apply this test, first look at the results of the operation:


The above node is updated by calling the Scheduleupdate method for self-location updates, and the following is an update using the Timer method. We can also see the menu entries for Start, remove, and Pausecurrenttarget, Resumecurrenttarget. They are used to operate on the scheduler. One thing to mention is that when the scheduler is turned on, we can identify whether the scheduler is turned on by acquiring the currently scheduled function, that is, by calling Isschedule. For the function itself, the update of the node itself can only be turned on or removed if it cannot detect its own update. This needs to be noted. For the bottom of the pause and resume, you can stop recovery for all the schedulers of the node. This is also a useful method.

Well, don't talk much. Let's take a look at the source code:

SchedulerTest.h:

#ifndef __scheduler_test__#define __scheduler_test__#include "cocos2d.h" Using_ns_cc;class schedulertest:p ublic Scene{public:static Scene *createscene (); virtual bool init (); Create_func (schedulertest); void update (float dt); void own_update (float dt);//function to prepare state void Readyfunc (float dt);p rivate : Size visiblesize;}; #endif
SchedulerTest.cpp:

#include "SchedulerTest.h" Scene *schedulertest::createscene () {Auto Scene = Schedulertest::create (); return scene;} BOOL Schedulertest::init () {if (! Scene::init ()) {return false;} Visiblesize = Director::getinstance ()->getvisiblesize ();//Current Test label description Auto Test_label = Label::createwithsystemfont ( "About Node ' s Update Test", "", "Test_label->setposition" (VEC2 (VISIBLESIZE.WIDTH/2, Visiblesize.height-test_ Label->getcontentsize ()); This->addchild (Test_label);/******************************************* Node one ****************************************************************/layercolor *block1 = Layercolor::create (color4b::red, This->addchild); Block1->ignoreanchorpointforposition (False) (BLOCK1); ); Block1->setanchorpoint (Vec2::anchor_middle); Block1->setposition (VISIBLESIZE.WIDTH/4, VisibleSize.height * 3/4-50);//Set the name to get Block1->setname ("Block1");//name tag attached to node one auto Label1 = Label::createwithsystemfont ("Block1", "", block1->addchild);(Label1); Label1->setposition (Block1->getcontentsize ()/2);//Node A status label, for the state, you need to dynamically change it, so you need to set a name auto State_ Label1 = Label::createwithsystemfont ("Block1 State:", "", "), State_label1->setposition (VEC2 (state_label1-> Getcontentsize (). Width/2,block1->getpositiony () + block1->getcontentsize (). height); This->addchild ( STATE_LABEL1) Auto state1 = Label::createwithsystemfont ("Stop", "" "," + "); State1->setposition (VEC2 ( VISIBLESIZE.WIDTH/2, State_label1->getpositiony ())); This->addchild (state1);//Set the name to get State1->setname (" State1 ");/******************************************************************* node two ****************************** /layercolor *block2 = layercolor::create (color4b::red, N.); This->addchild ( BLOCK2); Block2->ignoreanchorpointforposition (false); Block2->setanchorpoint (vec2::anchor_middle); block2- >setposition (VEC2 (Block1->getpositionx (), Block1->getpositiony ()-160);//Set the name to get Block2->setname (" Block2 ");/append the name tag on node two auto Label2 = Label::createwithsystemfont ("Block2", "", "); Block2->addchild (Label2);label2-> SetPosition (Block2->getcontentsize ()/2);//node two status label Auto State_label2 = Label::createwithsystemfont ("Block2 state: "," ","; State_label2->setposition (VEC2 (State_label2->getcontentsize (). Width/2,block2->getpositiony () + block2->getcontentsize (). Height), this->addchild (STATE_LABEL2), Auto State2 = Label::createwithsystemfont (" Stop "," ","); State2->setposition (VEC2 (Visiblesize.width/2,state_label2->getpositiony ()));this-> AddChild (State2); State2->setname ("State2");/*************************************************************** Menu entry ****************************************************************//******* node Start menu entry for node-on scheduler ******/ menuitemlabel* start_menuitem1 = menuitemlabel::create (Label::createwithsystemfont ("Start", "", ","), [&] (Ref* Sender) {//modify BLOCK1 status Auto state = Dynamic_cast<label*> (This->getchildbyname ("state1")); STATE-&GT;setstring ("Running ...");//Open the current node updatethis->scheduleupdate ();//Set Current Click Target is not available auto Start_item = dynamic_cast <MenuItemLabel*> (sender); start_item->setenabled (false);//Get Remove and set to Available click auto Menu = dynamic_cast< Menu*> (This->getchildbyname ("menu")), Auto Remove_item = dynamic_cast<menuitemlabel*> (menu-> Getchildbyname ("Remove_item1")); remove_item->setenabled (true);}); Start_menuitem1->setposition (VEC2 (Start_menuitem1->getcontentsize () WIDTH/2-VISIBLESIZE.WIDTH/2, Start_ Menuitem1->getcontentsize (). height-10)); Start_menuitem1->setname ("Start_item1"); auto start_menuitem2 = Menuitemlabel::create (Label:: Createwithsystemfont ("Start", "" "," + "), [&] (Ref *sender) {if (!isscheduled (cc_schedule_selector Wn_update)) {//Set current click Target not available auto Start_item = dynamic_cast<menuitemlabel*> (sender); start_item->setenabled ( FALSE);/******************************************* Open the Custom node update: Open after 3 seconds, call every 1 seconds, always on * * parameter correlation: **param1 cc_ Schedule_selector (SChedulertest::own_update): function **param2 1.0f: Call once every second **PARAM3 repeat call **PARAM4 first turn on scheduler delay time, here is 4 seconds **************** /this->schedule (Cc_schedule_selector (schedulertest::own_update), 1.0f, Cc_repeat_ FOREVER, 4.0f);//Open another scheduler, ready to open This->schedule (Cc_schedule_selector (Schedulertest::readyfunc), 1.0f, 3, 0);}); Start_menuitem2->setposition (VEC2 (Start_menuitem2->getcontentsize () WIDTH/2-VISIBLESIZE.WIDTH/2,-150)); Start_menuitem2->setname ("start_item2"); Remove menu entry for/******* node, for removing node scheduler ******/menuitemlabel *remove_ MenuItem1 = Menuitemlabel::create (Label::createwithsystemfont ("Remove", "" "," + "), [&] (Ref *sender) {// Modify the BLOCK1 status auto State = Dynamic_cast<label*> (This->getchildbyname ("state1")); State->setstring ("Removed ");//close updatethis->unscheduleupdate ();//Set current target not available auto Pause_item = dynamic_cast<menuitemlabel*> (sender); Pause_item->setenabled (false);//Get start and set to clickable auto menu = dynamic_cast<menu*> (This->getchildbyname ("MENU ")), Auto Start_item = dynamic_cast<menuitemlabel*> (Menu->getchildbyname (" start_item1 ")); start_item- >setenabled (True);}); Remove_menuitem1->setposition (VEC2 (Start_menuitem1->getpositionx () + start_menuitem1->getcontentsize (). Width * 2,start_menuitem1->getpositiony ())); Remove_menuitem1->setenabled (FALSE); Remove_menuitem1->setname ("Remove_item1"); auto remove_menuitem2 = Menuitemlabel::create (Label:: Createwithsystemfont ("Remove", "", "), [&] (ref* sender) {if (isscheduled (cc_schedule_selector Wn_update)) {//modify BLOCK2 status Auto state = Dynamic_cast<label*> (This->getchildbyname ("State2"));state-> SetString ("removed"); This->unschedule (Cc_schedule_selector (schedulertest::own_update));//Set current target not available auto Remove_item = dynamic_cast<menuitemlabel*> (sender); remove_item->setenabled (false);//Get start and set to clickable auto menu = dynamic_cast<menu*> (This->getchildbyname ("menu")); auto Start_item = dynamic_cast<menuitemlabel* > (menu-> Getchildbyname ("start_item2")); start_item->setenabled (True);}}); Remove_menuitem2->setposition (VEC2 (Start_menuitem2->getpositionx () + start_menuitem2->getcontentsize (). Width * 2,start_menuitem2->getpositiony ())); Remove_menuitem2->setenabled (FALSE); Remove_menuitem2->setname ("remove_item2");/******* node's Pause menu entry, which pauses all schedulers of the current node ******/auto Pause_menuitem = Menuitemlabel::create (Label::createwithsystemfont ("Pausecurrenttarget", "", "), [&] (ref* sender) {// Pauses all schedulers in the current node This->getscheduler ()->pausetarget (this);//Set current target not available auto Remove_item = dynamic_cast< Menuitemlabel*> (sender); remove_item->setenabled (false);//Get resume and set to clickable auto menu = dynamic_cast<menu* > (This->getchildbyname ("menu")), Auto Resume_item = dynamic_cast<menuitemlabel*> (menu-> Getchildbyname ("Resume_item")); resume_item->setenabled (true);//Modify BLOCK1 state Auto State1 = dynamic_cast<label* > (This->getchildbyname ("state1")); if (state1->getstring () = = "Running ...") {state1-&Gt;setstring ("Pause");} Modify the Block2 state auto State2 = dynamic_cast<label*> (This->getchildbyname ("State2")); if (isscheduled (cc_ Schedule_selector (schedulertest::own_update)) | | Isscheduled (Cc_schedule_selector (Schedulertest::readyfunc))) {state2->setstring ("Pause");}}); Pause_menuitem->setposition (VEC2 (0,pause_menuitem->getcontentsize (). Height * 3-visiblesize.height/2)); Pause_menuitem->setname ("Pause_item");/******* node's resume menu entry, which restores all schedulers of the current node ******/auto Resume_menuitem = Menuitemlabel::create (Label::createwithsystemfont ("Resumecurrenttarget", "", "), [&] (ref* sender) {// Restores all schedulers of the current node This->getscheduler ()->resumetarget (this);//Set current target not available auto Remove_item = dynamic_cast< Menuitemlabel*> (sender); remove_item->setenabled (false);//Get pause and set to clickable auto menu = dynamic_cast<menu* > (This->getchildbyname ("menu")), Auto Pause_item = dynamic_cast<menuitemlabel*> (menu-> Getchildbyname ("Pause_item"));p ause_item->setenabled (TRUE);//Modify BLOCK1 state Auto State1 = dYnamic_cast<label*> (This->getchildbyname ("state1")); if (state1->getstring () = = "Pause") {state1-> SetString ("Running ..."); Modify the Block2 state auto State2 = dynamic_cast<label*> (This->getchildbyname ("State2")); if (isscheduled (cc_ Schedule_selector (schedulertest::own_update)) {state2->setstring ("Running ...");}); Resume_menuitem->setposition (VEC2 (Pause_menuitem->getpositionx (), Pause_menuitem->getpositiony ()- Resume_menuitem->getcontentsize (). Height * 2)); Resume_menuitem->setenabled (FALSE); Resume_menuitem->setname ("Resume_item");//Menu Auto menu = Menu::create (Start_menuitem1, START_MENUITEM2, Remove_ MenuItem1, REMOVE_MENUITEM2, Pause_menuitem, Resume_menuitem, NULL); Menu->setname ("menu"); This->addchild ( menu); return true;} Node self-updating function void Schedulertest::update (float dt) {//cclog ("The node ' S update:%f ...", DT);//Determine the direction of the node static int dir1 = 1;// Gets the child node of the current node by name auto Block1 = dynamic_cast<layercolor*> (This->getchildbyname ("Block1")); VEC2 pos = VEC2 (bloCk1->getpositionx () + 3 * dir1, Block1->getpositiony ()); if (Pos.x > visiblesize.width-block1-> Getcontentsize (). WIDTH/2 | | Pos.x < Block1->getcontentsize (). width/2) {dir1 =-dir1;} Block1->setposition (POS);} own self-updating function void Schedulertest::own_update (float dt) {//log ("This is My Own update:%f ...", dt); static int dir2 = 1;//obtained by name The child node of the current node auto Block2 = dynamic_cast<layercolor*> (This->getchildbyname ("Block2")); VEC2 pos = Vec2 (Block2->getpositionx () + 3 * dir2, Block2->getpositiony ()); if (Pos.x > Visiblesize.width-block2 ->getcontentsize (). WIDTH/2 | | Pos.x < Block2->getcontentsize (). width/2) {dir2 =-dir2;} Block2->setposition (POS);} The state-ready function void Schedulertest::readyfunc (float dt) {static int i = 4;i--;//modifies Block2 state auto states = dynamic_cast<label* > (This->getchildbyname ("State2")) state->setstring (String::createwithformat ("Ready to start:%d second", I )->getcstring ()); if (i = = 0) {i = 4;//modify the Block2 status auto State = Dynamic_cast<laBel*> (This->getchildbyname ("State2")) state->setstring ("Running ...");//Get Remove.auto menu = dynamic_cast <Menu*> (This->getchildbyname ("menu")), Auto Remove_item = dynamic_cast<menuitemlabel*> (menu-> Getchildbyname ("remove_item2")); remove_item->setenabled (True);}}

In fact, there are many ways to get nodes, nodes have their own tag and name, and nodes are added and added in the form of rendering in the scene, so once the node is rendered, it can be obtained in different ways. This can be obtained by tag or name, provided that the tag or name must be set.

The above code I also made a more detailed comments, not much to say, have not understand can also put forward to ha ~

Okay, the self-updating function of the node update and the use of the timer will be here, the next article about the action class related. With it, but also for the scene of the object added a lot of "luster" Ha ~



The path of COCOS2DX learning----12th (on the Update of node nodes ' self-updating function and the use of timers)

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.