Cocos2d-x observer mode is actually very simple !! -- Game development: Zhao Yun to fight (13); Zhao Yun to fight

Source: Internet
Author: User
Tags notification center

Cocos2d-x observer mode is actually very simple !! -- Game development: Zhao Yun to fight (13); Zhao Yun to fight

Here isEvankakaWelcome to the discussion and exchange ~~~~~~

 Reprinted please indicate the source

This paper mainly explains in detail the observation mode in the Design Mode and Its simple application in the Coco2d-x, finally, combined with the skill cooling class amplification in the game for a use.

Cocos2d-x version: 2.2.5

Project Environment: Windows 7 + VS2010

Open Method: place the project in the project folder under the cocos2d-x installation directory open with

Let's take a look at the effect:


1. Introduction to observer Mode

The observer mode (sometimes referred to as the publish/subscribe mode) is a software design mode. In this mode, a target object manages all observer objects that depend on it and actively sends notifications when its status changes. This is usually done by calling the methods provided by various observers. This mode is usually used to implement an event processing system. In my other blog post, I learned the design pattern in 24 days-Observer pattern. Here is a more detailed introduction. If you are interested, please refer to it.

During Game Development, we often need to transmit data and messages between layers, between scenarios, and between scenarios. The Cocos2dx framework uses the observer mode to encapsulate a CCNotificationCenter class for us, it is also called the message and notification center. It is also a singleton class.

In the observer mode, the ccicationicationcenter class is the target object (subject) in the Observer mode, while the ccicationicationobserver class is the observer. A target object can register multiple observers. When the status of the target object changes, it can notify the observer object to respond accordingly. This is the implementation of the standard observer mode. However, the ccicationicationcenter is slightly different. Instead of notifying the observer by changing its status, the CCNotificationCenter explicitly sends messages of interest to the observer, the message name is used to identify whether the observer is interested. Each time a message is sent to the ccicationicationcenter, The ccicationcenter traverses all the observers, finds the observer who registered the message identifier, and sends the message to them.


1. Add an observer:

You can listen to a message anywhere as long as you are interested in it (just like listNotification in pureMVC.

void addObserver(CCObject* target,SEL_CallFuncO callBack,const char* name, CCObject* data);

Parameter 1 is the event listening target, parameter 2 is the callback function (that is, the function executed after receiving the message), parameter 3 is the message name, and parameter 4 is the message body.

The specific implementation is as follows:

2. Send a message: Call the postNotification method where the message needs to be sent. There are two postNotification Methods: no data or data.
void postNotification(const char* name);void postNotification(const char* name,CCObject* data);

Name is the message name, which is the unique identifier of the message and is unique throughout the game. Therefore, we generally put all the message names in a header file, and the textile message names are repeated, data is the message body, that is, the sent data.

The notification is as follows:

3. Release the message observer:

It is important to release the message observer. If you do not release the message, memory leakage will occur. We need to release the message observer in the Destructor method.

CCNotificationCenter: sharedNotificationCenter ()-> removeObserver (
Name // message name
Ii. Example 1. Use the observer mode in a layer

First, create a HelloWord project, and then add HelloWorldScene. h

<Span style = "font-size: 18px;"> // Add the void ObserverFunction (CCObject * object) called after the target notification observer. </span>
Open HelloWorldScene. cpp and add it in the init () function.

// Register the Message. If the Message is received, run ObserverFunctionCCNotificationCenter: sharedNotificationCenter ()-> addObserver (this, callfuncO_selector (HelloWorld: ObserverFunction), "Message", NULL );
Then HelloWorld ::~ Add HelloWorld:

// Note that the Message must be released at the end; otherwise, the content will be leaked to the CCNotificationCenter: sharedNotificationCenter ()-> removeObserver (this, "Message ");
Then implement the function:

// Add the event void HelloWorld called after the target notification observer: ObserverFunction (CCObject * object) {CCLOG ("You Click menuButton ");}

Next, we can notify the event to all observations ~, Here, I directly change the menu button event of the project (which was originally exited):

// The first parameter is the message name, and the second parameter is the message Value of the CCObject * type, that is, the message you want to send. ccicationicationcenter: sharedNotificationCenter () -> postNotification ("Message", NULL );

See the results:

The observation mode can not only notify updates, but also transmit data. Let's take a look at the 2nd examples below.

2. Use the observation mode for two different layers

(1) first, create a HelloWord project, and then create a layer-class SecondLayer

Header file SecondLayer. h

<Span style = "font-size: 18px;"> # ifndef _ SecondLayer_SCENE_H __# define _ SecondLayer_SCENE_H __# include "cocos2d. h "class SecondLayer: public cocos2d: CCLayer {public: virtual bool init ();~ SecondLayer (); static cocos2d: CCScene * scene (); CREATE_FUNC (SecondLayer); // Add the void ObserverFunction (CCObject * object) called after the target notification observer );}; # endif/_ secondlayer_scene_h__</span>

Implement file SecondLayer. cpp

# Include "SecondLayer. h "USING_NS_CC; CCScene * SecondLayer: scene () {CCScene * scene = CCScene: create (); SecondLayer * layer = SecondLayer: create (); scene-> addChild (layer); return scene;} SecondLayer ::~ SecondLayer () {// note that the Message must be released at the end. Otherwise, the content is exposed to CCNotificationCenter: sharedNotificationCenter ()-> removeObserver (this, "Message");} bool SecondLayer :: init () {if (! CCLayer: init () {return false;} // register the Message. If the Message is received, run ObserverFunctionCCNotificationCenter: sharedNotificationCenter ()-> addObserver (this, callfuncO_selector (SecondLayer :: observerFunction), "Message", NULL); return true;} // Add the event void SecondLayer: ObserverFunction (CCObject * object) called after the target notification observer) {CCLOG ("SecondLayer Receive num = % d", (int) object );}

(2) Use

Add the header file # include "SecondLayer. h" to HelloWorldScene. cpp"

Add the following to the init () function:

SecondLayer* second=SecondLayer::create();this->addChild(second,0);
Rewrite the project menu button event:

Void HelloWorld: menuCloseCallback (CCObject * pSender) {int num = CCRANDOM_0_1 () * 1000; // Random Number of 0-CCNotificationCenter: sharednotifcenter ()-> postNotification ("Message ", (CCObject *) num); // transmits data to the observer}
(3) effect:

Now, the SenondLayer class can receive the message from the target!

3. Use the observer mode in Zhao Yun to fight

Previously we designed a skill cooling class, don't know how long it will take to see the Cocos2d-x skill cooling here? --- Game development "zhao Yun to fight" (9), which is a layer class. Now we want to implement it. Once we press the button with special skills, zhao Yun is about to release special skills (zoom in). Here my idea is to set up an observer in the Hero class (that is, Zhao Yun). Once you observe that you have pressed the button for special skills, in addition, the skill is not cool-down, So Zhao Yun stops all actions and directly scales up the moves.

Add the Hero class header file Hero. h

// Skill special effect void SkillAmiation (CCObject * object); // note that a parameter is required because it is a function called in the Observer mode and does not prompt "type conversion ": cannot be converted from "void (_ thiscall Hero: *) (void)" to "cocos2d: SEL_CallFuncO"
In the Hero. cpp file of the Hero class implementation file, the initialization Hero InitHeroSprite (char * hero_name) function is added.

// Register MessageSkill. if the message is received, run SkillAmiationCCNotificationCenter: sharedNotificationCenter ()-> addObserver (this, callfuncO_selector (Hero: SkillAmiation), "MessageSkill", NULL );

Once you observe that the skill button is pressed, call the function:

// Skill special effect void Hero: SkillAmiation (CCObject * object) {m_HeroSprite-> stopAllActions (); // The current genie stops all animation CCAnimation * animation = CCAnimation: create (); for (int I = 1; I <= 6; I ++) {char szName [100] = {0}; sprintf (szName, "skill_mongod.png", I ); animation-> animation (szName); // frame for loading the animation} animation-> setDelayPerUnit (0.1f); animation-> setRestoreOriginalFrame (true); animation-> setLoops (5 ); // animation loop // wrap the animation into an action CCAnimate * act = CCAnimate: create (animation); // create a callback action and call AttackEnd () after the attack ends () CCCallFunc * callFunc = CCCallFunc: create (this, callfunc_selector (Hero: AttackEnd); // create a continuous action CCActionInterval * skillattack = CCSequence: create (act, callFunc, NULL); IsAttack = true; m_HeroSprite-> runAction (skillattack );}

Finally, remember to release:

Hero ::~ Hero (void) {// note that the message must be released at the end. Otherwise, the content will be leaked. CCNotificationCenter: sharedNotificationCenter ()-> removeObserver (this, "MessageSkill ");}
Then in the SkillButton. cpp BeginSkill () function, this class can see how long the Cocos2d-x skill cool? --- Game development Zhao Yun fight (9)
Add a sentence:

// The first parameter is the message name, and the second parameter is the message Value of the CCObject * type, that is, the message you want to send. ccicationicationcenter: sharedNotificationCenter () -> postNotification ("MessageSkill", NULL );

Okay, OK ,:

4. Observer Mode 1. Advantages:

Abstract coupling between the target object and the observer is realized. In this example, abstract coupling between the message and the observer is realized. You can define a one-to-multiple relationship between messages and message processing objects without worrying about implementation details.

2. Disadvantages

If an object to be observed has many direct and indirect observers, it takes a lot of time to notify all the observers.

3. Applicable scenarios

(1) An abstract model has two aspects, one of which depends on the other. Encapsulate these aspects in independent objects so that they can be changed and reused independently.

(2) The change of an object will lead to the change of one or more objects, without knowing how many objects will change, which can reduce the coupling between objects.

(3) An object must notify other objects without knowing who these objects are. You need to create A trigger chain in the system. The behavior of object A will affect object B, and the behavior of object B will affect Object C ......, You can create a chain trigger mechanism in observer mode.

For more information about the observation mode, see the 24-day design mode-Observer mode.


These days have been cool and it is not easy to write a good blog. This article has been written in my draft box for a long time. I can't write more than 2 MB of GIF animation, but I don't know how many images have been written! CSDN: You have to change this function. The game has added a sound. Unfortunately, it cannot be heard .... After watching the movie for two nights, this game has not been updated. I suggest you go to "dear" (very touching, remember to bring your own paper towels ..), The rise of the planet (), the Tai Chi (), and the movie family (funny. I 've been talking nonsense again. I haven't talked so much nonsense for a long time. This game is about to end, and I want to go to 3.3 again. The next game will fly out!

Related Article

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: 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.