Zhiyi game development tutorial cocos2d-x porting edition 002 (on)

Source: Internet
Author: User
ArticleDirectory
    • Scenario (ccscene)
    • Cclayer)
    • Genie (ccsprite)
    • Director (ccdirector)
    • Ccdirector (directors)
    • Ccscene (scenario)
    • Cclayer)
    • Ccsprite (genie class)
    • Summary
Basic Concepts

In order to fully grasp the development of cocos2d-x, we first need to understand the basic concepts of the engine. In fact, these basic concepts are essential for all game development, not cocos2d-x proprietary. Any game is made up of objects targeted by these concepts. The complexity of the game determines the complexity of these objects.

Scenario (ccscene)

Let's assume that a game has only two levels: the first level (two little devils and one little boss) and the second level (five little devils and one big boss ). In general, we design the entire game process (workflow) as follows ):

The opening animation has the following purposes:
Brief Introduction to game operations
Background
Company or Studio animation logo

After entering the main menu, you can guide the user:
Start a new game
Read progress
Set game sound, text, and game content ......
High-score ranking is usually a list, which is arranged by scores.
Help operations
Exit

Next, players can have a variety of options, regardless of the start of the new game or read progress, the game will enter the preset level. During the game, the first level of victory enters the second level, and the second level of victory enters the final victory screen (playing a video or displaying text on the background ), after confirmation, enter the ranking screen to see how many points have been scored this time. If a failure occurs, the screen that ends with the failure is displayed. Click OK to go to the main menu and start again.
It can be seen that the player's game process is to jump between the preset pictures, jump to different pictures according to the player's operation results (select the menu item, destroy the enemy or be killed by the enemy.
The scenes that make up the game process are what we call the scenario, which is represented by a black box. Obviously, different scenarios provide different operations, which can be roughly divided into the following scenarios:

Display scenario: play a video or simply output text on the image to implement the game's opening introduction, victory/failure tips, help instructions, and so on.
Options: Main Menu, game parameter settings, etc.
Game scenario: This is the main content of the game. In addition to this scenario, other types of scenarios are basically implemented by a general framework.

How can different functions be implemented in different scenarios? In each scenario, different functions are implemented through the superposition and combination of different layers. Therefore, a scenario is usually composed of one or more layers.

Cclayer)

Layer is the focus of our game writing. We spend more than 99% of our time implementing our game content on the layer. As shown in, a simple main menu screen is implemented by adding three layers:

Careful readers may have noticed that these layers are transparent or translucent in order to allow different layers to be combined to produce a unified effect. (Otherwise, we can only see the top layer)
Layer superposition is ordered. The background layer numbered 1 is at the bottom, the 2 is in the middle, and the 3 is at the top. Cocos2d-x is also in this order to stack the screen, in the top of the opaque part will overwrite the following content.
This order is also used for event response mechanisms in programming models. That is, Layer 3 first receives the system event (click the screen event with a finger), followed by Layer 2 and Layer 1. When an event is transmitted, if one layer processes the event, the layer at the end will no longer receive the event.
We can simply understand the layer as a window in Windows Programming (hwnd, winform, and tform in Delphi ).
In order to facilitate the game development, cocos2d-x from the technical implementation perspective to provide some public layer: processing menu with the menu layer, processing color display color layer.
Each layer can contain a variety of content elements: Text, links, Genie, maps, and so on. Among them, genie is the focus of the game.

Genie (ccsprite)

Genie is the main object of game development and processing. Enemy planes and tanks are system-controlled genie. Players control our planes as well as Genie. Even a random cloud or bird flying over is an genie.
Technically speaking, genie is an image that can be changed constantly. These changes include displacement, rotation, scaling, and frame switching.
A game is a game that allows a player to interact with one or more genie controlled by the system: melee, remote shooting, and conversation.

Director (ccdirector)

We have probably learned about the overall architecture of a game. Different scenarios are composed of different layers, and each layer contains genie movements on it. A player is playing a game by playing an genie or menu item on the operation layer, and switching between different scenarios.
Well, some readers of OO programming have already guessed the role of the Director object. Yes, according to the object-oriented design principles and reverse dependency principles: the genie should not rely on the layer, the layer should not rely on the scenario, and the scenario should not rely on the entire process. The director is the representative of the entire process. He is responsible for scenario switching during the game process.
There is usually only one director, so this object is Singleton ). The cocos2d-x framework has already been pre-defined for this instance and we can use it directly without additional creation.
The request of the Director object receiving layer object/scenario object is switched based on the pre-designed process. So far, we can outline the overall framework of a game and the correspondence between key cocos2d-x objects and it:

Note: at any time, only one ccscene object instance is active. This object can be used as the container of the current game content object. For Menu objects, it usually belongs to the main layer of the current scenario. The above is the main architecture of a game.
In fact, for each game scenario, different scenarios (checkpoints), each layer (static and dynamic), and each object (enemies, US, and China)Cube. This is the first step.

Implementation class of cocos2d-x

Next, we will first introduce the objects of cocos2d-x corresponding to the above basic concepts one by one, andProgramAssociation.

Ccdirector (directors)

The ccdirector object is similar to the main window object in Windows Programming (the difference is that this object is not visible). It is responsible for creating and managing the main window of the application/game, displays a scenario under a specific condition.

Call for ccdirectorCode(The following code is a standard step when the main program starts. It is implemented in the applicationdidfinishlaunching member function of appdelegate ):

 1   Bool Appdelegate: applicationdidfinishlaunching ()
2 {
3 // Initialize Director
4 Ccdirector * pdirector = ccdirector: shareddire ();
5 Pdirector-> setopenglview (& cceglview: Export dopenglview ());
6
7 // Enable high resource mode (2x, such as iphone4) and maintains low resource on other devices.
8 // Pdirector-> enableretinadisplay (true );
9
10 // Turn on display FPS
11 Pdirector-> setdisplayfps (True );
12
13 // Set FPS. The default value is 1.0/60 if you don't call this
14 Pdirector-> setanimationinterval ( 1.0 / 60 );
15
16 // Create a scene. It's an autorelease object
17 Ccscene * pscene = helloworld: Scene ();
18
19 // Run
20 Pdirector-> runwithscene (pscene );
21 Return True ;
22 }

Obviously, we can see that the ccdirector object can be used to complete the following two types of tasks:

Set the Display Properties of the main program window.

The following content is set in sequence:
1. initialize the ccdirector object.
2. Set whether to enable the retina display mode.
3. Set whether to display FPS.
4. Set the number of frames displayed per second on the game screen. The default value is 60.

Management and display scenarios.

The ccdirector object can only display one scenario at a time. To facilitate the management of scenario objects, the ccdirector object has three attributes related to the scenario (see ccdirector. h ):

1/*Current display scenario*/
2Ccscene * m_prunningscene;
3
4/*Next scenario to be displayed*/
5Ccscene * m_pnextscene;
6
7/*Scenario queue to be executed*/
8Ccmutablearray <ccscene *> * m_pobscenesstack;

At the same time, ccdirector provides the following methods for Object Management:

 1      /*  It is used to display the first scenario after the main program is started. If a running scenario already exists, it is unavailable.  */ 
2 Void Runwithscene (ccscene * pscene );
3
4 /* Suspend the currently running scenario, press it into the queue of the scenario to be executed, and start executing the new scenario */
5 Void Pushscene (ccscene * pscene );
6
7 /* A scenario pops up from the queue of the scenario to be executed, and replaces the current running scenario.
8 If the queue for execution is empty, the program stops running. */
9 Void Popscene ( Void );
10
11 /* Directly replace the current scenario with one scenario, which is the most common method. */
12 Void Replacescene (ccscene * pscene );
13
14 /* Stop running and release the current scenario. */
15 Void End ( Void );
16
17 /* Pause the scenario. The screen still exists, but the time task is stopped. */
18 Void Pause ( Void );
19
20 /* Resume the scenario. */
21 Void Resume ( Void );
Ccscene (scenario)

The scene object is relatively simple at present, and the current version of cocos2d-x (1.0.1) basically does not have any special features attached, it can basically be seen as a container of a layer (cclayer) object. Some examples do not use ccscene for scenario switching, but directly use layer transformation. I suggest you do not do this. Ccscene plays an important role. To add an animation effect for scene switching, ccscene is essential.

Cclayer)

The main functions of cclayer are as follows:
1) receives the touch operation input.
2) receives an accelerometer input.

In addition, the cclayer object itself does not provide more functions. We will focus on the interaction between cclayer objects and touchdispatcher.

Cocos2d-x in order to make it easy to use, directly provides the following 4 layers:

Cclayercolor (color layer)

This is transparent. You can set the fill color layer according to RGB. You can use setcontentsize to set the layer size and change the color block size. The red part in the figure is an instance of cclayercolor.

The layer also supports action to change color, fade in and fade out, and mix.

Cclayergradient (gradient layer)

Cclayergradient is a subclass of cclayercolor. It can draw gradient color on the background.

Ccmenu (menu layer)

This is a collection class using ccmenu objects. ccmenuitem instances form menu management selection screen layers with various buttons. (Note: The instance in this layer must be an instance of the ccmenuitem class or its subclass)
The ccmenu class provides methods for displaying ccmenuitem instances in a horizontal, vertical, or multi-row order.
To achieve different button effects, the system provides multiple types of ccmenuitem, but each button has three basic statuses: Normal, selected, and disabled.
Next, we will introduce the ccmenuitem class systems one by one:
Ccmenuitem
Ccmenuitem is a base class. Do not use this class directly. As the parent class of all menu items, ccmenuitem mainly performs the following two tasks:
1. Set the button status.
2. process the callback function (when the button is clicked, the function to be called is called the callback function ).Specifically, an nsinvocation * invocation is built in to implement unified callback function activation. (After this in-depth study and then modify it, in the cocos2d-x is certainly not)

Ccmenuitemlabel
Ccmenuitemlabel can convert any ccnode that supports the cclabelprotocol Protocol into a menu item and increase the zoom-in effect when selected.

Ccmenuitematlasfont/ccmenuitemfont
Both ccmenuitematlasfont and ccmenuitemfont inherit from ccmenuitemlabel. They can generate tags based on your provided strings and create menu items. The difference is that ccmenuitematlasfont uses image sets and ccmenuitemfont uses default fonts.

Ccmenuitemsprite
Ccmenuitemsprite has three ccnode objects that support the ccrgbaprotocol protocol, indicating images in normal, selected, and disabled states.

Ccmenuitemimage
Ccmenuitemimage is derived from ccmenuitemsprite. You only need to provide the image name. The process of creating a ccsprite object is automatically completed by the framework.

Ccmenuitemtoggle
There is a ccmenuitem array inside, which is used to display different states and achieve status switching.

Cclayermultiplex (Composite Layer)

This is a composite layer that can contain multiple layers and will be introduced in detail in the future.

Ccsprite (genie class)

Genie are the main static and dynamic targets in the game (enemy monsters, our operation targets ). Specifically, it is an independent image block. Generally, it is an action of motion: displacement, rotation, scaling, and motion-The motion effect formed by a continuous gradient image. We can directly set the attribute of the genie to allow him to exercise, or through action to achieve the same purpose.

In the cocos2d-x, the genie is implemented by the ccsprite class. The genie allows sub-objects to be included. When the parent object changes, the sub-objects change accordingly.
Since more than 95% of the content in the game is simulated by the genie class, how to improve the efficiency of the genie class execution is a critical issue.

1) cache the image content to reduce the number of reads to files with the same content.
Through the cctexturecache class, the cocos2d-x library indexes all the image files that are read during runtime according to the file name as the primary key. When the file name is the same, the system directly returns an image in the memory instead of reading the file.
All implementations related to image files uniformly call single-instance objects of the cctexturecache class at the underlying layer to ensure minimum system Io operations and improve program running efficiency.
2) Submit painting in batches to reduce the number of OpenGL function calls.
Through the ccspritebatchnode class, the cocos2d-x library submits all the child ccsprite objects of the ccspritebatchnode class object to OpenGL output at a time.
There is also a class called ccspriteframecache, which is used to manage all frames of animation effects. The implementation of this class also calls the cctexturecache class object.

Summary

At this point, the reader of several key concepts of cocos2d-x and the corresponding implementation class has a holistic grasp. Ccscene, cclayer, and ccsprite classes are derived from the ccnode class. From the perspective of class objects, they are the same and can be mutually dependent. From the perspective of game design, their functions are different from each other, with their respective focus:

Ccscene is used:
1) As the overall container object of a scenario, all content objects (menus, statuses, game roles, and NPC) are included. The cascade relationship is determined by the zorder of addchild of ccnode.
2) Special Effects of scenario switching. Because all scenario switching effects are derived from the ccscene subclass cctransitionscene.

Cclayer is used to handle input problems:
1) handle touch events
2) power perception Processing

Ccsprite is used to display a variety of genie and game content.

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: info-contact@alibabacloud.com 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.