Using helloworld to explain the programming ideas and key points of cocos2d-x
In this paper, the helloworld of cocos2d-x is used as an example to explain the characteristics and key points of the cocos2d-x engine. 2.2 in order to display the new functions, the new features including screen self-adaptation are added to the helloworld project code, but also increase the difficulty of getting started with new people, I will not talk about it, just say a few key words of code, for has understood the cocos2d-x architecture of friends, the content behind this article does not help you, I can follow my writing "improve cocos2d-x", but I may not have written at the moment ). Of course, it is impossible to clarify all the content from the very beginning. First of all, you must understand the two main points if you want to start a game or write an example.
Key Aspect 1:
About plotting. When I was new to cocos2d-x, many of my friends couldn't wait to find the plotting function and asked me if I had a function like drawimage () or drawstring. Here I want to say a few more words, the bottom layer of the cocos2d-x has been a simple encapsulation of the painting, we do not need to explicitly write drawImage) such a function.
How can we understand this? For example, to make a game, we often separate the logic layer from the drawing layer. In the logic layer, there may be many levels, but the current player only has one level, and there are maps and many enemy troops in the level. We perform logical operations on the logic layer to change the status and coordinates of the enemy soldiers. Then, on the drawing layer, draw the enemy soldiers on the screen and the visible area of the map to the screen. This is the classic logical-draw-logic-draw) structure.
And just get started with friends can so understand, cocos2d-x has been drawn code written, we only need to set in the logic layer. In the cocos2d-x, there is the concept of scene), the current scene only one, scene has a lot of ccsprite genie), a ccsprte has x, y, reference pictures of these attributes, the Cocos2d-x constantly draws the visible genie in the current scene to the screen. Therefore, if we want to draw a background image in the cocos2d-x, first create a scene, then create a genie and add it to the scene in some form, set the referenced image and sprite location, and remember to set scene to the current scenario. See the code below.
650) this. width = 650; "style =" background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; border-top: 0px; border-right: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; "title =" clip_image001 "border =" 0 "alt =" clip_image001 "src =" http://www.bkjia.com/uploads/allimg/131229/12154H514-0.png "height =" 183 "/>
First look at main. cpp
# Include "main. h"
# Include "../Classes/AppDelegate. h"
# Include "CCEGLView. h"
USING_NS_CC;
IntAPIENTRY_tWinMain (HINSTANCEhInstance,
HINSTANCEhPrevInstance,
LPTSTRlpCmdLine,
IntnCmdShow)
{
UNREFERENCED_PARAMETER (hPrevInstance );
UNREFERENCED_PARAMETER (lpCmdLine );
AppDelegateapp;
CCEGLView * eglView = CCEGLView: Export dopenglview ();
EglView-> setViewName ("HelloCpp ");
EglView-> setFrameSize (2048,1536 );
EglView-> setFrameZoomFactor (0.4f );
ReturnCCApplication: sharedApplication ()-> run ();
}
Here, I just need to remember that the eglview-> setFrameSize (w, h) function is used to set the view size.
The main. cpp file in vs is the entry of the Program on the win32 platform. A window is created here, with the size of 2048,1536)
SetFrameZoomFactor0.4f) is used to reduce the window size by 0.4 times. To take care of small screen users like me, it is still a headache.
So I set the window to 480X320, blocking the zoom window.
650) this. width = 650; "style =" background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; border-top: 0px; border-right: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; "title =" clip_image002 "border =" 0 "alt =" clip_image002 "src =" http://www.bkjia.com/uploads/allimg/131229/12154MX3-1.png "height =" 181 "/>
Look at AppDelegate. h.
# Ifndef_APP_DELEGATE_H _
# Define_APP_DELEGATE_H _
# Include "cocos2d. h"
ClassAppDelegate: privatecocos2d: CCApplication
{
Public:
AppDelegate ();
Virtual ~ AppDelegate ();
VirtualboolapplicationDidFinishLaunching ();
VirtualvoidapplicationDidEnterBackground ();
VirtualvoidapplicationWillEnterForeground ();
};
# Endif // _ APP_DELEGATE_H _
AppDelegate is the control class of the program, which contains three functions: applicationDidFinishLaunching, applicationDidEnterBackground, applicationWillEnterForeground)
After the program is started, the program is suspended and enters the background. The program is executed when it is returned from the background. The definition must be implemented by ourselves.
Let's see how applicationDidFinishLaunching is implemented in AppDelegate. cpp.
BoolAppDelegate: applicationDidFinishLaunching (){
CCDirector * pDirector = CCDirector: shareddire ();
CCEGLView * pEGLView = CCEGLView: Export dopenglview ();
PDirector-> setOpenGLView (pEGLView );
CCSizeframeSize = pEGLView-> getFrameSize ();
# If (CC_TARGET_PLATFORM = CC_PLATFORM_WINRT) | (CC_TARGET_PLATFORM = CC_PLATFORM_WP8)
PEGLView-> setDesignResolutionSize (designResolutionSize. width, designResolutionSize. height, kResolutionShowAll );
# Else
PEGLView-> setDesignResolutionSize (designResolutionSize. width, designResolutionSize. height, kResolutionNoBorder );
# Endif
Vector <string> searchPath;
If (frameSize. height> mediumResource. size. height)
{
SearchPath. push_back (largeResource. directory );
PDirector-> setContentScaleFactor (MIN (largeResource. size. height/designResolutionSize. height, largeResource. size. width/designResolutionSize. width ));
}
Elseif (frameSize. height> smallResource. size. height)
{
SearchPath. push_back (mediumResource. directory );
PDirector-> setContentScaleFactor (MIN (mediumResource. size. height/designResolutionSize. height, mediumResource. size. width/designResolutionSize. width ));
}
Else
{
SearchPath. push_back (smallResource. directory );
PDirector-> setContentScaleFactor (MIN (smallResource. size. height/designResolutionSize. height, smallResource. size. width/designResolutionSize. width ));
}
CCFileUtils: sharedFileUtils ()-> setSearchPaths (searchPath );
PDirector-> setDisplayStats (true );
PDirector-> setAnimationInterval (1.0/60 );
CCScene * pScene = HelloWorld: scene ();
PDirector-> runWithScene (pScene );
Returntrue;
}
As mentioned above, cocos2d-x2.2 has added a lot of new feature-related code in the helloworld example, a major section here is related to screen self-adaptation, so you can skip.
Key code:
Starting
CCDirector * pDirector = CCDirector: shareddire ();
CCDirector is a game management class. Its instance is a global one. It is obtained through the static function CCDirector: shareddire(), through which game settings can be obtained, it can also be used to control which scenario is currently running.
Look at the end of the function.
PDirector-> setDisplayStats (true );
This code is set to display the number of frames running the game on the screen. If frames are dropped, they will be immediately seen.
650) this. width = 650; "style =" background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; border-top: 0px; border-right: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; "title =" clip_image003 "border =" 0 "alt =" clip_image003 "src =" http://www.bkjia.com/uploads/allimg/131229/12154M356-2.png "height =" 87 "/>
The current number of frames is 60, and each rendering times is 3
PDirector-> setAnimationInterval (1.0/60 );
This setting sets the interval of each frame of the game to 1/60 seconds.
CCScene * pScene = HelloWorld: scene ();
PDirector-> runWithScene (pScene );
The last two sentences are to call the HelloWorld: scene function to create a ccscene, and then run the scenario I mentioned earlier). Then, the genie in the scene will be drawn to the screen.
Call runWithScenepScene for the first running scenario). If you want to switch from one scenario to another, you need to call replaceScenepScene );
Our ccscene is created by calling the static function HelloWorld: scene. In this scenario, there is a background text label and a button.
Before reading the HelloWorldScene class, we should first popularize other key points of knowledge.
Key Aspect 2:
1. layer: There is a layer between scene and sprite. In general, we need to create one or more layers, add layers to the scenario, and then put the genie into the layer. With the use Layer Management wizard
After the concept, we can divide a scenario into multiple layers when playing games, such as the map layer and Object layer, and the bullet layer in the special effect layer) and the ui Layer. You can set the occlusion relationship between layers.
You can also set the display or not display of a layer to shield the layer. Layer and layer can also contain parent-child relationship). For example, a map layer can be
It is divided into four small layers. These four small layers are added with four types of genie, spring, summer, autumn, and winter, to form a map of four kinds of scenery. Then, only one layer is displayed as needed to achieve the effect of seasonal changes in a scenario.
At the same time, because the layer class inherits the cocos2d-x touch interface class, we can implement a certain layer of finger touch behavior.
2. node Structure: CCNode node) is a relatively underlying base class in the cocos2d-x, we commonly used CCScene, CCLayer, CCSprite class inherited CCNode. CCNode has container Functions
There is a children Member, which is a queue). Each ccnode can contain other ccnodes. The addchildm_other_node function is used to add other nodes as their own subnodes. This relationship becomes a parent-child relationship.
The parent node is called the parent node), and the parent node becomes child. Because of this node feature of ccnode, we can add layer to scene and sprite to layer. Form a tree structure.
650) this. width = 650; "style =" background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; border-top: 0px; border-right: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; "title =" clip_image004 "border =" 0 "alt =" clip_image004 "src =" http://img1.51cto.com/attachment/201311/4/8148702_13835855246KNX.png "height =" 201 "/>
3. Memory Management Reference Counter and code style): Skip this section if you cannot understand it. The retain and release mechanisms of the cocos2d-x reference counter mechanisms) from objective-c. In java and c #, when an object is not referenced by anyone
The memory will be automatically released. In c ++, the new object generated by the programmer must be deleted by himself. And in cocos2d-xobjective-c. Most of the objects we create inherit the CCObject class, which has a counter. Generally
The new object. The counter is 1. If we use retain for it, the counter will add 1. If we use release for it, the counter will be-1. When the counter is 0, the object will be destructed. In parallel with reatinrelease, there is also an auotorelease
If we set a ccobject to autorelease, it will be added to a pool. When its counter is 1, it will be automatically released in a certain period of time. If we get a ccobject, how do we know the number of its counters?
What about auotorelease? Here, there is a syntax specification. As long as it is not a new object, but is obtained through other interfaces such as helloworld: scene), it should be autorelease, and for us, its counter is 1. should be even if it
If the object is retained by the external retain, it will inevitably appear in pairs by the external release at a certain time to ensure that the memory is not leaked). Therefore, if we only need to use this object, and there is no guarantee that no external release will be made before this, so we should manually retain it.
And release it when it is not needed. For example, when CCDirector switches to a scenario, it will retain it to ensure that it will not be released. During the next switchover, it will be release, this will not cause the scenario to never be released. The release only means that we do not need it.
This object does not mean that the object will be released at this time, because it may be retained elsewhere, and this object is also required ).
Based on this premise, the classes we generally write will not expose the constructor, so that newClassX can be directly written elsewhere), but will encapsulate a static function create) make sure that others can get an instance object with the auotorelease counter as 1 for it.
In the create FUNCTION, we create an object, execute the initialization function init), set it to autorelease, and return it. The old version of the cocos2d-x in order to be consistent with the cocos2dobjective-c version) interface, using the class name) writing.
For example, CCNode: Node () has been abandoned by the new version because it is not suitable for c ++.
The following describes the HelloWorldScene code and the header file.
# Ifndef _ HELLOWORLD_SCENE_H __
# Define _ HELLOWORLD_SCENE_H __
# Include "cocos2d. h"
ClassHelloWorld: publiccocos2d: CCLayer
{
Public:
Virtualboolinit ();
Staticcocos2d: CCScene * scene ();
VoidmenuCloseCallback (CCObject * pSender );
CREATE_FUNC (HelloWorld );
};
# Endif/_ HELLOWORLD_SCENE_H __
HelloWorld is a class that inherits CCLayer. There is an init function in it which is an initialization function. A static function scene returns a scene, which is added with a cclayer.
We mentioned that there is a Beijing text label and a button in the HelloWorldlayer. menuCloseCallback is the callback function after the button is clicked.
Where does the create FUNCTION go? CREATE_FUNC (HelloWorld), which is a macro. Because most classes have the create static function, the content is a new object pointer and init). It is annoying to set it to auotorelworld and then return it.
Code will get longer, so the cocos2d-x has written a lot of such macros for us. The translation is
StaticHelloWorld * create ()
{
HelloWorld * pRet = newHelloWorld ();
If (pRet & pRet-> init ())
{
PRet-> autorelease ();
ReturnpRet;
}
Else
{
DeletepRet;
PRet = NULL;
ReturnNULL;
}
}
I have saved a lot of lines of code, but I usually don't bother to use macros. These lines of code are actually easy to write.
It can be seen that the main initialization content is written in the init) function. Go to the cpp file.
# Include "HelloWorldScene. h"
# Include "AppMacros. h"
USING_NS_CC;
CCScene * HelloWorld: scene ()
{
CCScene * scene = CCScene: create ();
HelloWorld * layer = HelloWorld: create ();
Scene-> addChild (layer );
Returnscene;
}
BoolHelloWorld: init ()
{
If (! CCLayer: init ())
{
Returnfalse;
}
CCSizevisibleSize = CCDirector: shareddire()-> getVisibleSize ();
CCPointorigin = CCDirector: sharedDirector ()-> getVisibleOrigin ();
CCMenuItemImage * pCloseItem = CCMenuItemImage: create (
"CloseNormal.png ",
"CloseSelected.png ",
This,
Menu_selector (HelloWorld: menuCloseCallback ));
PCloseItem-> setPosition (ccp (origin. x + visibleSize. width-pCloseItem-> getContentSize (). width/2,
Origin. y + pCloseItem-> getContentSize (). height/2 ));
CCMenu * pMenu = CCMenu: create (pCloseItem, NULL );
PMenu-> setPosition (CCPointZero );
This-> addChild (pMenu, 1 );
CCLabelTTF * pLabel = CCLabelTTF: create ("HelloWorld", "Arial", TITLE_FONT_SIZE );
PLabel-> setPosition (ccp (origin. x + visibleSize. width/2,
Origin. y + visibleSize. height-pLabel-> getContentSize (). height ));
This-> addChild (pLabel, 1 );
CCSprite * pSprite = CCSprite: create ("HelloWorld.png ");
PSprite-> setPosition (ccp (visibleSize. width/2 + origin. x, visibleSize. height/2 + origin. y ));
This-> addChild (pSprite, 0 );
Returntrue;
}
VoidHelloWorld: menuCloseCallback (CCObject * pSender)
{
# If (CC_TARGET_PLATFORM = CC_PLATFORM_WINRT) | (CC_TARGET_PLATFORM = CC_PLATFORM_WP8)
CCMessageBox ("Youpressedtheclosebutton. windowsstore?donotimplementaclosebutton.", "Alert ");
# Else
CCDirector: sharedDirector ()-> end ();
# If (CC_TARGET_PLATFORM = CC_PLATFORM_IOS)
Exit (0 );
# Endif
# Endif
}
Static function scene) returns a scene, which contains a HelloWorld, which is a layer ).
When creating HelloWorld, it is obtained by calling the create FUNCTION. the create FUNCTION calls the init function. See the init function below.
First, execute the initialization function of the parent class, and then get the screen size.
CCSizevisibleSize = CCDirector: shareddire()-> getVisibleSize ();
CCPointorigin = CCDirector: sharedDirector ()-> getVisibleOrigin ();
In the earlier version, getwinSize is used ). Here, we will show you the screen self-adaptation in version 2.2, which is the one we didn't describe in appdelegate before. Due to the relationship between screen self-adaptation,
Although we have set the view size in the main function, it does not mean that the entire view can be drawn to the screen. It may only be drawn from the middle part, and the extra part will not be visible, getVisibleSize) the function is to obtain the printable
GetVisibleOrigin is the size of the output part. You can draw the coordinates of the lower-left vertex and the lower-left vertex of the view ).
650) this. width = 650; "style =" background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; border-top: 0px; border-right: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; "title =" clip_image005 "border =" 0 "alt =" clip_image005 "src =" http://www.bkjia.com/uploads/allimg/131229/12154G2K-4.png "height =" 244 "/>
The example of hellowWorld is to enlarge the aspect ratio to no Black edge, which may cause the upper and lower sides or some left and right sides to be invisible, the starting coordinates and the length and width of the displayed part can be used to locate the genie on the screen.
Lower left (origin. x, origin. x + visibleSize. height/2 ),
Bottom right (origin. x + visibleSize. width, origin. x + visibleSize. height/2 ),
Or in the middle (origin. x + visibleSize. width/2, origin. x + visibleSize. height/2)
CCMenuItemImage * pCloseItem = CCMenuItemImage: create (
"CloseNormal.png ",
"CloseSelected.png ",
This,
Menu_selector (HelloWorld: menuCloseCallback ));
PCloseItem-> setPosition (ccp (origin. x + visibleSize. width-pCloseItem-> getContentSize (). width/2,
Origin. y + pCloseItem-> getContentSize (). height/2 ));
CCMenu * pMenu = CCMenu: create (pCloseItem, NULL );
PMenu-> setPosition (CCPointZero );
This-> addChild (pMenu, 1 );
One of the original menu items of the CCMenuItemImage class is a button consisting of two image genie). Its create FUNCTION has four parameters. The first parameter is the image name, they are the images to be displayed before clicking.
The displayed image. The next two parameters are the callback object to be executed after the click and the pointer to the callback function. menu_selector (HelloWorld: menuCloseCallback) is used to simulate the selector in objective-c,
Menu_selector is a macro. In fact, the content is to convert the function pointer into a function pointer of CCObject. If you don't understand it, it doesn't matter. Just write it.
PCloseItem-> setPosition (ccp (origin. x + visibleSize. width-pCloseItem-> getContentSize (). width/2, origin. y + pCloseItem-> getContentSize (). height/2 ));
SetPositionx, y) The function is used to set Node coordinates.
GetContentSize) returns the Node size.
PCloseItem is placed in the lower right corner of the screen.
However, because CCMenuItemImage does not implement the cocos2d-x touch interface, you need to put it into a CCMenu to click.
CCMenu is the menu container class, In the cocos2d-x2.2 it inherits layer previously said layer inherits the touch interface), so it has a touch behavior, equivalent to a menu layer. Add the original menu to CCMenu, and then CCMenu
You can see the button and click it.
PMenu-> setPosition (CCPointZero );
This-> addChild (pMenu, 1 );
The coordinates of pMenu are 0, 0, and the buttons are in the lower right corner of the screen relative to pMenu. Therefore, pMenu is in the lower right corner of the screen relative to the layer.
Note: this-> addChild (pMenu, 1); here, an additional number is passed in the addchild function. this parameter is the Z value. A layer has a lot of energy. What is the occlusion relationship during painting. The answer is that if the value of Z is large, it will ensure that it is drawn in
The z value is smaller. The Z value passed to pMenu is 1, and the values smaller than 1 will be under pMenu. If the Z value is not input, the default value is 0.
MenuCloseCallback is the callback function for clicking the button. It contains different processing code based on the predefined macros of CC_TARGET_PLATFORM.
The CC_TARGET_PLATFORM macro is a platform macro. Because our platform is win32, the compiled code is just one sentence.
CCDirector: sharedDirector ()-> end (); this function means to close the program.
CCSprite is a class for associating images. When we want to add an image object, CCSprite is created. Therefore, we use the CCLabelTTF class for text.
CCLabelTTF * pLabel = CCLabelTTF: create ("HelloWorld", "Arial", TITLE_FONT_SIZE );
PLabel-> setPosition (ccp (origin. x + visibleSize. width/2, origin. y + visibleSize. height-pLabel-> getContentSize (). height ));
This-> addChild (pLabel, 1 );
The creation function of the CCLabelTTF class input three parameters: text content, Font, and size.
The created pLabel is located on the top of the screen.
The set Z value is also 1, but it is added later, so it is on the menu layer.
CCSprite * pSprite = CCSprite: create ("HelloWorld.png ");
PSprite-> setPosition (ccp (visibleSize. width/2 + origin. x, visibleSize. height/2 + origin. y ));
This-> addChild (pSprite, 0 );
Finally, we create a background and add it to the scenario.
The CCSprite creation function only needs to input an image name. In fact, there are three reloads, but they are temporarily unavailable ).
The image is placed in the center of the screen, and the input Z value is 0, so it will be drawn at the bottom.
The parsing of the HelloWorld Code itself ends here.
Ps: note that the CCSprite we created is not directly new because it is obtained through the create interface, so we should regard it as actually) The counter is 1 and autorelease, so it won't be destroyed.
In fact, because it is added to the layer, when CCNode adds a child, it will automatically add 1 to the child counter and-1 to the removal. Therefore, we do not need to manually retain it. When the current scenario is destroyed
The child node is removed and destroyed.
Some may say that my blog post is rough and many related points are not detailed. Here I want to explain that I do not intend to translate the meaning of each sentence of code as a translator.
The purpose is to familiarize myself with the code style and framework of the cocos2d-x engine, so I say a few more to the counter and node structure. Helloworld is a simple example, but in the version of the cocos2d-x2.2, because developers want to show many new features, new function interfaces, added a lot of relatively difficult to understand the code, this increases reading difficulty and is not suitable for reading at the beginning. Now that you are writing a tutorial, you must be able to help new users quickly get started and reduce the difficulty. By, you can transfer the knowledge points to the readers. Readers who have read this article will be able to figure out how to create a scene and a genie and draw it on the screen.
The blog will have two branches later
1: I have always believed that programmers can play games as long as they can map images. Then I will write a few simple game examples, from simple to difficult. The initial code does not even consider screen resolution does not apply to animations, and then slowly implement these features, each time you add several common classes of cocos2d-x or are the applicable and illustration of the mechanism. It may initially be a simple small game such as playing balloons, or a slightly larger project such as tower guard or rpg. Friends following this line will learn more easily. The only enemy may be the speed at which my blog is updated.
2: cocos2d-x comes testcpp example is actually very classic, many friends are too lazy to read, I intend to explain one by one, then my blog has a similar tool book role. You can follow this line when you are getting started. But I don't know if it means it can be updated.
When learning cocos2d-x, we must follow the framework of the engine, write code according to the cocos2d-x style, strictly abide by the retainrelease mechanism, there will be no inexplicable compilation of the code can not pass the situation. Finally, I wish you good night. In the next blog, we will start playing games. Let's keep up with your spirit.