Environment Construction 0 Engine Introduction
Cocos2d-x is an open-source 2d game engine designed to encapsulate the underlying drawing code (OpenGL), simplifying the development of 2D games. It is a prototype of the Cocos2d, which first appeared on the IPhone (Cocos2d-iphone). Later Chinese developers (Touch technology) The Cocos2d-iphone was ported to make it a cross-platform game engine (currently supporting almost all major mobile operating systems such as Ios,windows,android,tizen,blackberry).
Currently the latest version of Cocos2d-x is 3.2, has supported 3D features, so the current cocos2d-x is not just a 2D game engine. Currently the number of games on the phone is based on cocos2d-x development, including the turret saga/I call mt/fishing talent/three kills and so on.
1 Version Selection
Although the latest version has now evolved to 3. x version, but since the latest version has added the C11 feature, it is required that the development environment must support C11, which means that the version of Visual Studio must be higher than VS12, but because VS12 requires that the operating system version is Win7 SP1, we are currently unable to meet the computer. So we chose the 2.1.4 version (the legend of the turret was developed using this version) for development.
The following are the required software to build the environment:
1.COCOS2DX 2.1.4
2.Android ndk-r10c (due to a variety of strange problems in earlier versions of NDK, the COCOS2DX compilation fails, it is recommended to use the latest version of R10C)
3.Android SDK
4.Tizen 2.2 (Version 2.3 does not currently have sufficient documentation to support the method of successfully compiling COCOS2DX on version 2.3)
5.vs2010 Express (currently the highest version supported by Win7, if the system is not restricted, you can choose to install the updated version)
6.Cygwin (Linux emulation environment on Windows, Android Local compilation required)
7.Python (V2.7)
With these software installed, you can start COCOS2DX development (if you only need to run on Windows, install only 1 and 5).
2 Creating Windows Projects
Since we are developing on Windows, we will first create a Windows project.
Enter the Tools\project-creator directory under the COCOS2DX 2.1.4 directory, and the command line executes the following command:
Python create_project.py-project mygame-package com. Mycompany.game-language CPP
Where project and package names need to be named according to individual needs.
After the command executes successfully, the corresponding name item is found in the projects directory under the COCOS2DX 2.1.4 directory.
Go to the Proj.win32 directory under the project and start writing programs with VS open projects.
The project will be connected to five LIB libraries by default, please do not modify these 5 lib libraries. Run the current project directly and we can see the cocos2dx version of Hello World.
In this way, we can already develop the Windows version of the game here.
3 Developing Android Projects
So how does a developed Windows game run on Android?
3.1 Creating an Android project
Re-enter the directory where cocos2d-x-2.1.4 is located and open the file create-android-project.bat for editing.
Set the _cygbin,_androidtools,_ndkroot in the file to the bin directory of Cygwin, the tools directory of the Android SDK, and the directory where the NDK resides.
Configure it to look like the following, and then save it.
Set _cygbin=e:\cygwin\binif not exist "%_cygbin%" echo couldn ' t find Cygwin at "%_cygbin%" & Pause & Exit 4set _an Droidtools=e:\development\android-sdk\toolsif not exist "%_androidtools%" echo couldn ' t find Android SDK tools at "%_andr oidtools% "& Pause & Exit 5set _ndkroot=e:\development\android-ndk32-r10b-darwin-x86.tar\android-ndk-r10bif Not exist "%_ndkroot%" echo couldn ' t find ndk at "%_ndkroot%" & Pause & Exit 6
Click the run Create-android-project.bat file, enter the package name as required, and the project name, and the program will create an Android project directory named after the project name in the directory where cocos2d-x-2.1.4 is located.
The next step is to copy the classes and resources directories that were previously developed in the projects directory to the Android project directory.
3.2 Compiling Android projects
Next we need to compile the Android project, go to the Proj.android\jni directory under the project folder, open the Android.mk file for editing, modify the Local_src_files, and add all the CPP files you have written, for example:
Local_src_files: = Hellocpp/main.cpp . /.. /classes/appdelegate.cpp. /.. /classes/helloworldscene.cpp. /.. /classes/bulletlayer.cpp. /.. /classes/enemy.cpp. /.. /classes/enemylayer.cpp. /.. /classes/gamelayer.cpp. /.. /classes/gamescene.cpp. /.. /classes/lifecirclelogger.cpp. /.. /classes/planelayer.cpp. /.. /classes/welcomelayer.cpp. /.. /classes/welcomescene.cpp. /.. /classes/bomplayer.cpp \
Exit after saving.
Next use Cygwin to enter the Proj.android directory, execute./build_native.sh start compiling.
If you cannot find the NDK error, you need to perform the following two sentences first:
NDK_ROOT=/CYGDRIVE/D/DOWNLOADS/ANDROID-NDK-R10C Export Ndk_root
Where Ndk_root is the directory where the NDK resides.
It should be noted that because of the different compilers used by the NDK and the VC used, there may be a variety of compilation problems during the compilation process. With the latest version of the NDK you can solve most problems, and the remaining specific issues should be modified according to the different procedures.
(It has to be said that you may encounter a variety of strange problems during the process of compiling the NDK, but since 2.1.4 is a fairly extensive version of the app, you can find answers to all the questions you may have on Google)
If all goes well, after more than 10 minutes of compilation, there will be a library file generation (libgame.so).
3.3 Running Android projects
Next we need to import the project into eclipse.
After the project is imported there will be a android:icon error, after the fix, plug in the phone or open the virtual machine, the program can be compiled to run.
In this way, our game can be run on the Android phone.
4 Development Tizen Project
The COCOS2DX engine also supports Tizen, but the Tizen is much more complex.
Because Tizen is currently in a high-speed iteration, the versions are not even compatible with each other, so there are a number of help documents that are not available on the Web. I'm just going to do it now. Compile the game into a Tizen TPK, but now the card is on the security authentication of the signature, Temporarily unable to run. So the following we only talk about how to compile Tizen available TPK, system security issues are not discussed, interested students can be studied on this basis.
In addition, the following default is the Tizen SDK as well as the IDE.
Because we can't find a template to create a Tizen project at the moment, the Tizen IDE does not support directly creating a COCOS2DX project (you can create your own configuration, refer to Https://developer.tizen.org/zh-hans/documentation /articles/using-cocos2d-x-tizen-native-applications?langredirect=1). Therefore, it is relatively simple to modify the Tizen project provided by the demo directly at present.
Use the project under the Samples\cpp\hellocpp directory to move your code and resources into this project, first of all guaranteed to work properly under Windows.
Then copy the resource files into the Proj.tizen\res directory.
- Open the Tizen IDE and import a native Project
- Select the COCOS2DX directory, ensure that the following five items must be selected.
- The next step is to import your own Tizen project, which will typically have the following six items:
cocos2d-x/external/box2d/proj.tizencocos2d-x/external/chipmunk/proj.tizencocos2d-x/cocos2dx/ proj.tizencocos2d-x/cocosdenshion/proj.tizencocos2d-x/extenshions/proj.tizencocos2d-x/samples/cpp/testcpp/ Proj.tizen
- Next compile the first five library projects, and then a few 10 minutes after the first five library projects can be compiled to complete
- Open the Tizen virtual machine, compile your own Tizen project, and the compilation will fail normally. This is typically due to a problem with the C + + compiler's environment configuration, modifying the C + + compiler options in the project configuration, such as:
Find the computer and find the location of the missing files on the computer where the error was compiled, and add those directories to the libraries directory of C + + linker.
- Recompile the project, compile to generate TPK
- Refer to the official documentation for the program signature (https://developer.tizen.org/dev-guide/2.2.1/org.tizen.gettingstarted/html/tizen_overview/app_ sign.htm), install the program, you can execute (after signing or encounter various security issues, still not fully done)
Game development Overview
Cocos2d's
The game structure can be simply summed up as scenes, layers, sprites. Each game component can be added to another component to form a hierarchical relationship, for example, a scene can contain multiple layers, and a layer can contain multiple sprites.
Cocos2d-x classes are placed under the Cocos2d namespace. As an example of "Actions/ccaction.h" under the engine directory, we can see that there are two macros in the first file: Ns_cc_begin and Ns_cc_end. Looking at the definition of a macro, these two macros are equivalent to including all types in the Cocos2d namespace. In the game, we often use another macro using_ns_cc provided by the engine to refer to the Cocos2d namespace.
Cocos2d-x has a file "Cocos2d.h" that contains all the other header files. In general, we only need to include this header file when we use it, so we can use the full functionality of the engine.
Coordinate
In Cocos2d-x, there are two kinds of coordinate systems.
- The drawing coordinate system. It is the most common coordinate system, with the same coordinate system as OpenGL, with the lower-left corner as the origin, the right x-axis positive direction, and the y-axis positive direction upward. In Cocos2d-x, all drawing-related operations use the drawing coordinate system, such as Position in game elements and Anchorpoint and other properties.
- The texture coordinate system. The texture coordinate system is the origin point in the upper-left corner, the right x-axis positive direction, and the y-axis positive direction downward. In Cocos2d-x, this coordinate system is used only when a partial rectangle is truncated from the texture, such as the Texturerect property of Ccsprite.
The creation of a class
Cocos2d-x does not use traditional value types, all objects are created on the heap and then referenced by pointers. There are usually two ways to create a Cocos2d-x object: The first is to create an uninitialized object using the new operator, then invoke the Init series method to initialize it, and the second is to create an object directly using a static factory method ( Cocos2d-x's initialization method is prefixed with init, so it can be easily identified. The initialization method returns a Boolean value that represents whether the object was initialized successfully, and the factory method name is unified as create.
Both of these methods can create Cocos2d-x objects, but they still have a little bit of a difference in memory management. The object created with the constructor is owned by the caller, and ownership of the object created with the factory method does not belong to the caller, so the object created with the constructor requires the caller to be freed, and the object created using the factory method is not required.
When an object is created with a constructor, the reference count of the object is 1, so the caller needs to dispose of the object cautiously after use, while the reference count is 1 when the object is created using the factory method, but because the object has already been put in the recycle pool, the caller does not have a reference to the object unless we artificially invoke the Retain () to get the reference right, otherwise, you do not need to voluntarily dispose of the object.
There is no constructor in Objective-c, and creating an object requires allocating memory for the object and then invoking the initialization method to initialize the object, which is equivalent to the constructor in C + +. As with Objective-c, Cocos2d-x has taken this step. The constructors of the Cocos2d-x class usually have no parameters, and the parameters required to create the object are passed to the object through a series of initialization methods at the beginning of init.
To ensure that the initialization method can be overridden by subclasses, you need to ensure that the initialization method is declared as a virtual function.
Selector Selector
In Objective-c, the selector (Selector) is a mechanism similar to a class function pointer in C + +. Because Cocos2d-x inherits the code style of Cocos2d-iphone, it also provides a series of macros similar to those created in the selector syntax in objective-c to create function pointers. These macros have only one parameter, selector, that represents the class method being pointed to. These macros are listed as follows:
Schedule_selector (selector) Callfunc_selector (selector) Callfuncn_selector (selector) Callfuncnd_ Selector (selector) Callfunc_selector (selector) Menu_selector (selector) Event_selector (selector) Compare_selector (selector)
Ccdirector Director
Ccdirector's work is really similar to the director, who is responsible for the following tasks.
- Game rendering aspects, including setting the game rendering window, FPS display, the default frame rate limit, texture color bit width and so on.
- Toggles the current game scene, pausing or resuming the running of the game scene.
- All in all, the game is under the management of Ccdirector to complete the rendering settings and Process control.
Ccdirector plays the role of the big head of the whole world, so it is natural to adopt a single case design pattern. Anywhere in the program, it is accessed through the following simple code:
*ccdirector pdirector = Ccdirector::shareddirector ();
In Ccdirector, we define the following methods for managing scenarios.
Runwithscene (ccscene* Scene): Start the game and run scene scenes. This method is invoked the first time the main scene is started when the main program starts.
- Replacescene (ccscene* Scene): Toggles the scene by replacing the current scene directly with the incoming scene, and the current scenario is released. This is the most common way to switch scenes.
- Pushscene (ccscene* Scene): Pauses the currently running scene and presses it into the generation execution scenario stack, and then sets the incoming scene to the current running scene.
- Popscene: Releases the current scene, pops the top of the stack from the generation execution stack, and sets it as the current running scene. If the stack is empty, the app is ended directly. In pairs with pushscene, you can achieve the effect of entering the setup interface from the main interface and then back to the main interface.
- Pause: Pauses all timers and actions in the currently running scene, and the scene still appears on the screen.
- Resume: Resumes paused timers and actions in the current running scene. It is used in conjunction with pause.
- End: Ends the scene while exiting the app.
It is important to note that the above three ways to switch scenes (Replacescene, Pushscene, Popscene) are the scenes that are to be switched are fully loaded before releasing the currently running scene. So, in the moment when the new scene is completely loaded, there are two scenes in the system, which will be a test of memory, and if you don't pay attention, switching scenes may cause memory shortage.
Ccscene: Scene
The scene is just a layer container that contains all the game elements that need to be displayed.
For scenarios, the nodes we add are usually layers. The layer that is added first is placed below the layer that is added later.
Cocos2d-x offers a lot of gorgeous scene switching effects, such as page flipping, waves, fade in and fade in. These effects are implemented by Cctransitionscene series effects classes derived from Ccscene.
Cclayer: Layer
Like Ccscene, the layer also plays the role of a container. Unlike the scenario, however, the layer usually contains a direct rendering of the screen
Content: We need to put sprites, text tags or other game elements in the layer, set the properties of the game elements, such as position, direction and size, set the action of the game elements, and so on. Thus, most of the coding time for game development is spent on the creation layer.
ZOrder, which refers to the order of the child's z-axis, which is the order of the display, the greater the value, the higher the display position. The default value for ZOrder is 0.
tag is the identification number of the element, and if the tag value is set for the child node, it can be found using the tag value in its parent node.
Another very important feature of Cclayer is the ability to accept user input events, including touch, accelerometer, and keyboard input.
Ccsprite elf
Sprites are different from layers or scenes, which are subordinate to layers and are visible graphics in the scene. Player-controlled protagonists, AI-controlled NPCs, and chests, stones on the map, and even background images of the main menu of the game are sprites. Therefore, it can be thought that the players see almost everything is composed of elves.
The genie is not necessarily static. In general, an elf can be changed in a way that includes: move, rotate, scale, deform, show disappear, animate (like GIF animation), and so on. Sprites are combined in a hierarchical structure and interact with the player to form a complete game.
ccsprite* psprite = ccsprite::create ("helloworld.png");p sprite->setposition (CCP (SIZE.WIDTH/2, SIZE.HEIGHT/2)); This->addchild (psprite, 0); ccsprite* sprite1 = new Ccsprite (); Sprite1->initwithfile ("helloworld.png");
Ccnode
All game elements inherit from Ccnode, so they all have the features provided by Ccnode.
Ccnode defines a common feature of a drawing object, including position, scale, visibility, rotation angle, and so on.
Ccnode::addchild method: Used to add a game element to another element. When you create a layer or scene, you typically initialize your own game elements, define special effects, or combine other game elements, and the Addchild method is used to combine game elements.
Once the rendering tree is established, it is easy to organize complex scenes. We give each node a range of properties, including the position of the node relative to the parent node, the rotation angle, the scale and deform parameters, and so on. The advantage of the rendering tree is that we can create complex objects or actions on a per-layer basis simply by considering the properties of the nodes relative to the parent node.
A simple example is that the turtle in the "Fishing Man" is made up of the torso and 4 legs. In the game, not only is the turtle moving in the water, it
The 4 legs are also constantly doing the strokes. This series of actions can be broken down into: 4 legs rotate relative to the whole turtle at a certain angle; the torso is stationary relative to the whole turtle, and the whole turtle swims in the fish layer, and the position and direction are constantly changing.
Therefore, the establishment of a node to represent the turtle, under the Turtle node to establish a further 5 elves, representing 4 legs and torso respectively. In this way, each action is controllable, as long as you set the action for each node, you can complete the complex animation. Conversely, if there is no tree structure, the organization of a slightly more complex swimming will become a huge project.
Cocos2d also uses a render tree schema. Any visible game element is derived from the Cocos2d-x node (ccnode), and the common game elements are scenes (Ccscene), layers (Cclayer), and Sprites (ccsprite). As mentioned earlier, the game is usually organized in the order of scenes, layers, sprites, and each node has its own characteristics. However, in the actual development, in order to achieve some special effects, it is not necessary to rigidly adhere to this level of order. Layers or sprites are normal nodes, so even if you add sprites to sprites, add sprites to the scene, and even add layers to the Sprite, none of these actions are forbidden.
The most basic features of a node include:
- contains other Ccnode objects;
- Accepts various events and callback functions, such as timer events;
- Run the action.
Update Timer
Ccnode The Refresh event Update method, which is triggered once per frame before it is drawn.
CNode default does not enable the update event, in order to enable the timer, we need to call the Scheduleupdate method and reload update to execute its own code. Correspondingly, we can use the Unscheduleupdate method to stop the timer.
Schedule Timer
This->schedule (Schedule_selector (enemylayer::addenemy1), 0.5f);
The schedule method of Ccnode takes a function pointer and starts a timer, using different overloads of the schedule method to specify the trigger interval and delay. Schedule_selector is a macro that converts a specified function to a function pointer, which is used to create the function pointer required by the schedule method. The function that passes in the macro should contain a float parameter that represents the interval from the previous trigger event.
Ccmenuitemimage Menu
Ccmenuitemimage *pcloseitem =ccmenuitemimage::create ("closenormal.png",//normal state picture "closeselected.png",//press the picture in the state This,//Response object Menu_selector (Helloworld::menuclosecallback)); Response Function Pcloseitem->setposition (CCP (Ccdirector::shareddirector ()->getwinsize (). width-20, 20)); ccmenu* Pmenu = ccmenu::create (Pcloseitem, NULL); Pmenu->setposition (Ccpointzero); This->addchild (Pmenu, 1);
Ccaction Action
Ccaction is the base class for action classes, and all actions are derived from this class, and an object created by it represents an action. The action acts on the Ccnode, so any action needs to be performed by the Ccnode object.
ccsprite* Sprite = ccsprite::create ("Fish.png"); ccaction* action = ccmoveto::create (1.0f, CCP (0, 0)); Sprite->runaction (action);
A ccaction can only be used once, because the action object not only describes the action, but also preserves the constant change in the action.
Some of the intermediate parameters. For action objects that need to be reused, you can copy them using the Copy method.
The two main classes derived from Ccfinitetimeaction are instantaneous actions (ccactioninstant) and persistent actions (Ccactioninterval)
Instantaneous action
- Ccplace This action is used to place a node at a specified location, which is the same as modifying the Position property of a node
- Ccflipx and Ccflipy, respectively, are used to reverse the sprite along the X and Y axes, with the same effect as setting the Sprite's FlipX and FlipY-Properties.
- Ccshow and cchide are used to display and hide nodes, as they do with the visible property of the set node.
- Cccallfunc series actions include Cccallfunc, CCCALLFUNCN, CCCALLFUNCND, and Cccall-funco four actions, which are used to make method calls in the action. The method called by Cccallfunc does not contain parameters, and the method called CCCALLFUNCN contains a parameter of type ccnode* that represents the object that executed the action. The method called by CCCALLFUNCND contains two parameters, one node parameter and one custom parameter (ccnode* and void*). The method called by Cccallfunco contains only one parameter of type ccobject*.
Cclabelttf Label
cclabelttf* Plabel = cclabelttf::create ("Hello World", "Arial", 24); Ccsize size = Ccdirector::shareddirector ()->getwinsize ();p label->setposition (CCP (SIZE.WIDTH/2, Size.Height- ); This->addchild (Plabel, 1)
Action Ccaction
Action acts on the elements of the game, allowing the game elements to move. Common movements are moving, rotating, flashing, disappearing, and so on. Action is divided into continuous action and instantaneous action, continuous action in a period of time to complete, instantaneous action will be completed instantaneously. To make the game screen move, we create a series of actions when needed and apply them to the game elements. In Cocos2d-x, the action is implemented by the Ccaction class, and the Ccaction class derives the Interval of the persistence action class Ccaction ccactioninstant and the instantaneous action class. All actions are derived from one of the above two classes.
Animation ccanimation
Animation (animation) is a special kind of persistent action, which can only be applied to sprites to achieve frame animation effects. Like film footage, a frame animation is constantly switched on and off by several still images. A static picture is called a frame, and a sequence of frames represents an animated effect.
In Cocos2d-x, we can create frame animation sequences (ccanimation) with multiple frames and create frame animations (ccanimate) that can be used for sprites using frame animation sequences.
Log Cclog
Cclog ("Hello world!");
END
COCOS2DX Cross-platform use