Cocos2dx. 3x getting started trilogy-Hello Game project analysis (III), cocos2dx. 3x-hello
I. Prerequisites:
Complete the creation and compilation of the Hello Game project.
For details, see Cocos2dx. 3x_Hello Game project creation.
Ii. Objectives of this article:
L analyze the main components of the proj. win32 Project
L analyze the main components of the proj. android Project
L create a new MyScene. cpp and display it in the game.
L run on the android real machine to view the effect
Iii. Analysis:
This is usually the case for our game development. First, in Microsoft Visual Studio 2012, proj. compile the code of the win32 project and run the debugging in windows. After the game entity is developed, compile and package the so file, and then continue on the proj. write a small amount of code in the android project to complete the packaging and development of the game on the android platform.
L analyze the main components of the proj. win32 Project
Open the proj. win32 project with Microsoft Visual Studio 2012
Composition:
The entire hellogame solution consists of four Engineering Projects: hellogame, libbox2d, libcocos2d, and libSpine.
1. Hellogame project: The main game project. our development work is mainly completed in this project.
2. libbox2d Engineering: It simulates the C ++ physical engine of 2D rigid-body objects. The famous games such as plants vs. Zombies and angry birds have all contributed to this engine.
3. libcocos2d project: Needless to say, the entire cocos2dx Core
4. libSpine project: tool and software support library
Next we will mainly analyze the code of the Hellogame project. The libbox2d project will be explained in the subsequent physical engine articles. The other two projects will be explained in the subsequent sections.
HellogameSource code of the project:
The project consists of the AppDelegate. cpp, AppDelegate. h, HelloWorldScene. cpp, and HelloWorldScene. h files under the src directory, and the main. cpp and main. h files under the win32 Directory.
The source files under the src directory are code files shared by all six platforms. Both android and ios use the source files under this directory, which is part of the real cross-platform code.
The source file in the win32 Directory is only a main entry file, which calls the game on the win32 platform. In fact, in the corresponding proj. android project, there is also a main portal file corresponding to the android platform, just because the different implementation codes of the platform are different, but the purpose is the same.
AppDelegate. cppSource code:
AppDelegate is similar to the android Application. It provides Application-level status callbacks, and the entire game Application is controlled by this file method. The following describes and explains several main methods:
# Include "AppDelegate. h" # include "HelloWorldScene. h" // namespace macro. Introduce cocos2d header file USING_NS_CC; AppDelegate: AppDelegate () {} AppDelegate ::~ AppDelegate () {}// sets OpenGL context // This setting is valid for all platforms void AppDelegate: initGLContextAttrs () {// sets the OpenGL context attribute, currently, only six attributes can be set: // red, green, blue, alpha, depth, stencel GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView :: setGLContextAttrs (glContextAttrs);} // when the application is started, the game startup entry // here we start the first scene (scenario) // The loading interface is usually started here in a specific game. // your game starts from here! Bool AppDelegate: applicationDidFinishLaunching () {// initialize director auto director = Director: getInstance (); auto glview = director-> getOpenGLView (); if (! Glview) {glview = GLViewImpl: create ("My Game"); director-> setOpenGLView (glview );} // display FPS on the screen // we recommend that you enable this setting during development, you can have a general understanding of the performance of your game. // when the game is officially released, disable this setting director-> setDisplayStats (true ); // set the default FPS value to 1.0/60 ctor-> setAnimationInterval (1.0/60); // create a HelloWorld scene. this is the automatic recycle object auto scene = HelloWorld: createScene (); // tell director to run the scene ctor of HelloWorld-> runWithScene (scene); return true ;} // This method will be called when the game enters the background. // For example, press the home button of the android mobile phone during the game. // For example, when the game has a call, the following void AppDelegate is displayed :: applicationDidEnterBackground () {Director: getInstance ()-> stopAnimation (); // if your game uses SimpleAudioEngine, the pause code must be as follows: // SimpleAudioEngine: getInstance ()-> pauseBackgroundMusic ();} // This method will be called when the game is restored to the front-end. // For example, if the call ends, the void AppDelegate: applicationWillEnterForeground () {Director :: getInstance ()-> startAnimation (); // if your game uses SimpleAudioEngine, the restoration code must be as follows: // SimpleAudioEngine: getInstance () -> resumeBackgroundMusic ();}
As mentioned in the code above, ctor (director: Responsible for displaying and switching game scenarios, and controlling everything in the entire movie like a movie director) and scene (scenario: Responsible for displaying a game scenario, just like a movie scene ).
The most important method in the above Code is applicationDidFinishLaunching (), because your game starts from this method!
HelloWorldScene. cppSource code:
In the above Code, a HelloWorldScene scenario is created in the applicationDidFinishLaunching () method of the AppDelegate class and runs this scenario. HelloWorldScene. cpp is the specific code implementation of this scenario. The following describes and explains several main methods:
# Include "HelloWorldScene. h "USING_NS_CC; // create Scene scene * HelloWorld: createScene () {// create a self-released Scene object auto Scene = scene: create (); // create a self-released Image layer object auto layer = HelloWorld: create (); // Add the created image layer to the scene/You can add multiple image layers scene-> addChild (layer); // return the created scene return scene ;} // scenario initialization method bool HelloWorld: init () {// 1. first, initialize the parent class if (! Layer: init () {// returns false return false if the parent class fails to be initialized;} // obtains the visual screen Size of the entire mobile phone. Size visibleSize = Director: getInstance () -> getVisibleSize (); // obtain the coordinate Vec2 origin = Director: getInstance ()-> getVisibleOrigin () of the mobile phone's screen origin (); // create a closed button with an icon // call the menuCloseCallback method after clicking to exit the game auto closeItem = MenuItemImage: create ("CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1 (HelloWorld :: menuCloseCallback, this); // set the display position of the close button // It is displayed in closeItem-> setPosition (Vec2 (origin. x + visibleSize. width-closeItem-> getContentSize (). width/2, origin. y + closeItem-> getContentSize (). height/2); // create a menu that can be released automatically. auto Menu = menu: create (closeItem, NULL); menu-> setPosition (Vec2: ZERO ); this-> addChild (menu, 1); // create a Label auto label = Label: createWithTTF ("Hello Game ", "fonts/Marker Felt. ttf ", 24); // set the label display position in the screen label-> setPosition (Vec2 (origin. x + visibleSize. width/2, origin. y + visibleSize. height-label-> getContentSize (). height); // Add the label to the screen layer this-> addChild (label, 1); // create an image sprite auto Sprite = sprite :: create ("HelloWorld.png"); // set the sprite-> setPosition (Vec2 (visibleSize. width/2 + origin. x, visibleSize. height/2 + origin. y); // Add the image genie to the screen layer this-> addChild (sprite, 0); return true;} // exit button event void HelloWorld :: menuCloseCallback (Ref * pSender) {// when it is a wp8 or winrt platform # if (CC_TARGET_PLATFORM = CC_PLATFORM_WP8) | (CC_TARGET_PLATFORM = CC_PLATFORM_WINRT) messageBox ("You pressed the close button. windows Store Apps do not implement a close button. "," Alert "); return; # endif // end ctor: getInstance ()-> end (); // exit when it is the ios platform # if (CC_TARGET_PLATFORM = CC_PLATFORM_IOS) exit (0); # endif}
The above code is a simple Scene (scenario) implementation code. When we really develop a game, we actually create a scenario one by one and organize a complete game through Director.
L analyze the main components of the proj. android Project
Use eclipse to open the proj. android Project
Composition:
The whole hellogame is much simpler than win32, except for some components required by the android project:
1. Classes Folder: the source file is shared with proj. win32.
2. jni/hellocpp/main. cpp: This is equivalent to the source file under the win32 Directory in proj. win32, the main entry.
3. libs/armeabi/libcocos2dcpp. so: This is the compilation package of the entire game code. In fact, the real game code implementation is eventually compiled and packaged into this so class library by the C ++ file for android code to call and run the game.
The development of the entire game basically does not need to write code in eclipse. The android platform only needs to call the compiled so file to run the game, in eclipse, you only need to package the android project that contains the so file into an apk file and publish it.
L create a new MyScene. cpp and display it in the game.
Open the proj. win32 project with Microsoft Visual Studio 2012. We will add a new Scence (scenario) in this project and display it. This is a very simple task, but it will still encounter a lot of difficulties for new users, so here is a special demonstration.
File Creation:The cpp file contains two new methods,
1Method 1
Step 1:In Solution Explorer on the right, right-click src to create a class.
Problem: Here you will find that the "Browse" button cannot be used. The newly created cpp can only be created under the hellogame \ proj. win32 Directory, which leads to a problem.
Step 2:Regardless of this, follow the prompts and click "add" to enter the Class Wizard interface, enter the class name MyScene, and then click "create class". At this time, go to proj. myScene is added to the win32 Directory. cpp and MyScene. h.
2Method 2
Step 1:Right-click Solution Explorer on the right and choose src to create an item.
Problem: Here you will find that the "Browse" button can be used, click to change the directory to hellogame \ Classes, and select whether to create a. ccp file or. h file.
Step 2:Select the. cpp type, enter MyScene. cpp, and then create the MyScene. h file. At this time, the newly added MyScene. cpp and MyScene. h files will appear in the Classes directory.
Code writing:
MyScene. h:
# Include "cocos2d. h "class MyScene: public cocos2d: Layer {public: static cocos2d: Scene * createScene (); virtual bool init (); CREATE_FUNC (MyScene) ;}; MyScene. cpp: # include "MyScene. h "USING_NS_CC; Scene * MyScene: createScene () {auto scene = Scene: create (); auto layer = MyScene: create (); scene-> addChild (layer); return scene;} bool MyScene: init () {if (! Layer: init () {return false;} // obtain the visual screen Size of the entire mobile phone. Size visibleSize = Director: getInstance ()-> getVisibleSize (); // obtain the coordinate Vec2 origin = Director: getInstance ()-> getVisibleOrigin () for the mobile phone screen origin. // create a Label auto label = Label :: createWithTTF ("MyScene", "fonts/Marker Felt. ttf ", 24); // set the WHITE label-> setColor (Color3B: WHITE); // set the label position label-> setPosition (Vec2 (origin. x + visibleSize. width/2, origin. y + visibleSize. height-label-> getContentSize (). height); // Add the label to the screen layer this-> addChild (label, 1); return true ;}
After writing MyScene, you must add a button menu on the page after the game is enabled and click it to enter the MyScene scenario. The interface scenario after the game is turned on is HelloWorldScene, so we need to add a button in HelloWorldScene and add an event for this button to start MyScene.
HelloWorldScene. h:
In this file, declare a button first and click the event:
// Switch to the next scene event
Void menuNextCallback (cocos2d: Ref * pSender );
HelloWorldScene. cpp: 1. first introduce MyScene. h # include "HelloWorldScene. h" # include "MyScene. h" USING_NS_CC ;...... 2. Implement the menuNextCallback Event code // click the event button and start MyScenevoid HelloWorld: menuNextCallback (Ref * pSender) {// create a MyScene instance auto scene = MyScene :: createScene (); // Replace the current scene ctor: getInstance ()-> replaceScene (scene);} 4. Add the start button on the screen ...... // Set the display position of the close button. // It is displayed in closeItem-> setPosition (Vec2 (origin. x + visibleSize. width-closeItem-> getContentSize (). width/2, origin. y + closeItem-> getContentSize (). height/2); // create a button menu with images auto goItem = MenuItemImage: create ("next_1.png", "next_2.png", CC_CALLBACK_1 (HelloWorld: menuNextCallback, this); goItem-> setPosition (Vec2 (origin. x + visibleSize. width/2-closeItem-> getContentSize (). width/2, Origin. y/2 + closeItem-> getContentSize (). height/2); // create a menu that can be released from auto Menu = menu: create (closeItem, goItem, NULL); menu-> setPosition (Vec2 :: ZERO); this-> addChild (menu, 1 );......
So far, we have completed the compilation of all the code, and now start debugging and running to check the effect.
Problem:
At this time, if the MyScene created in method 2 can be compiled and run properly, and the MyScene created in method 1 cannot run through compilation, the following error will be reported:
Intelliisense: Unable to open the source file "MyScene. h"
Error C1083: Unable to open include file: "MyScene. h": No such file or directory
Solution:
Step 1:Right-click the project name and choose Properties.
Step 2:Select C/C ++ on the left and add:; $ (ProjectDir)
This is my own additional include directory. It should be different for different environments.
$ (EngineRoot) cocos \ audio \ include; $ (EngineRoot) external \ chipmunk \ include \ chipmunk; $ (EngineRoot) extensions ;.. \ Classes ;..; % (AdditionalIncludeDirectories );$ (ProjectDir)
After completing the above settings, the project can run properly after debugging and running, and click the button to successfully display the MyScene screen to achieve our set goal.
L run on the android real machine to view the effect
To run on an android real machine, you must first package and compile the so file.
Step 1:If MyScene is created using the first method, copy the MyScene. cpp and MyScene. h files from proj. win32 to the Classes folder. If MyScene is created using the second method, skip this step.
Step 2:Open the android. mk file under the proj. Android \ jni directory in the EditPlus text editor, add MyScene. cpp to the source file list to be compiled, and save the file as follows:
......
LOCAL_SRC_FILES: = hellocpp/main. cpp \
.../../Classes/AppDelegate. cpp \
../Classes/HelloWorldScene. cpp \
../Classes/MyScene. cpp
......
Step 3:Start Cygwin and start compiling and packaging the so file. If not, see Cocos2dx. 3x_Hello Game project creation.
Step 4:After successfully packaging the so file, enable eclipse to open the game project and connect to the android mobile phone to run the project to see if the running effect of the real machine is the same as that in the previous windows.
Conclusion:
Cocos2d-x3.3 entry trilogy to this even completed, next will take a specific game as a series of methods to continue in-depth practice, the first practical series: Cocos2d-x3.x tower defense game (protect radish) from scratch, the total number of articles in this series is to be determined, and the goal is not a rough exercise until a complete online-compliant game is completed.
The author communicated QQ: 2303452599
Email: mymoney1001@126.com