Previous: http://www.bkjia.com/kf/201208/148631.html
Cocos2d-x Study Notes (13) -- schedule
In the game, to detect when two moving objects collide or not, you must determine the matrix range of the two objects in each frame to determine whether there is an intersection. Similarly, some game animations, in order to make the animation effect, while setting the action, we also need to layout each frame of the screen, In the cocos2d-x can use schedule () the function is implemented.
The following is the definition of the schedule () function:
[Cpp]
Void CCNode: schedule (SEL_SCHEDULE selector)
{
This-> schedule (selector, 0 );
}
Void CCNode: schedule (SEL_SCHEDULE selector, ccTime interval)
{
CCAssert (selector, "Argument must be non-nil ");
CCAssert (interval> = 0, "Argument must be positive ");
Ccschedtor: sharedScheduler ()-> scheduleSelector (selector, this, interval ,! M_bIsRunning );
}
Here I only talk about the second function. The first parameter is the callback type. Here schedule_selector is used, for example, schedule_selector (MyClass: MyCallbackFunction). The second parameter is the interval, that is, how long does one call the MyCallbackFunction;
Step 1: Create the cocos2d-win32 project and name it scheduler;
Step 2: Add the following classes in HelloWorldScene. h:
[Cpp]
Class ScheduleTest: public CCLayer
{
Protected:
Int posX; // used to add the horizontal direction of the object each time the addTarget function is called.
Public:
ScheduleTest ();
Virtual void onEnter ();
Void addTarget (ccTime dt); // an genie is added for each call.
};
Step 3: Add the following functions to HelloWorldScene. cpp:
[Cpp]
ScheduleTest: ScheduleTest ()
{
PosX = 0;
}
Void ScheduleTest: onEnter ()
{
CCLayer: onEnter ();
Schedule (schedule_selector (ScheduleTest: addTarget), 1 );
}
Void ScheduleTest: addTarget (ccTime dt)
{
PosX + = 10;
CCSprite * player = CCSprite: spriteWithFile ("player.png ");
AddChild (player );
Player-> setPosition (ccp (posX, 100 ));
}
Modify the scene function in HelloWorldScene and change HelloWorld * layer = HelloWorld: node ();
ScheduleTest * layer = new ScheduleTest ();
Step 4: Compile and run the program. You can see that a character is added to the background every second;