A game full of action, adventure and puzzle where Masato needs to protect his village from one of the most powerful rogue ninja he as ever faced
In my previous article “Implementing MVC pattern for cocos2d-x projects” I had mentioned about a “Model” sending messages back to the “Controller” using delegate control. While the source code is located in the “GitHub”, I had few request regarding a bit more explanation on the usage of the delegate control mentioned in that article.
Posted by cobagames on Dec 24th, 2013
In my previous article "Implementing MVC pattern for cocos2d-x projects" I had mentioned about a "Model" sending messages back to the "Controller" using delegate control. While the source code is located in the "GitHub", I had few request regarding a bit more explanation on the usage of the delegate control mentioned in that article.
I will refer to the same source code as explained in the "MVC" article so that you can relate to this easier. We have a ball class and a Game Layer class. Game Layer sends command to the ball class to change its state (animation) and in return ball class returns a message back to the Game layer class using a delegate control. So how do we do this?
We will create a C++ header class called "GameplayLayerDelegate.h". This class will have a virtual method. In our example, we want to send a message back to the Gameplay layer class when the ball touches the ground, therefore we will call our virtual method as "touchGround" and this method will accept the position in the screen where the ball touches the ground (since this can be anywhere in the screen).
The GamePlayLayer class will inherit from this delegate header class as mentioned above:
As you can see that in the virtual method we have "= 0" in the end. This means that we force the inherited class to implement this virtual method otherwise your code will not build successfully. So we implement this virtual method in the GamePlayLayer class.
The ball class will declare the GamePlayLayerDelegate as a public variable:
In the GameplayLayer class, when we initialise the Ball sprite, we also set its delegate:
Now from the Ball class we can send a message back to the GamePlayLayer class using the delegate control and accessing the touchGround method implemented in the GamePlayLayer class: