Cocos2d-xna: horizontal strategic game development Experiment 4 Layer build rich interaction

Source: Internet
Author: User

This article mainly introduces the CCLayer and CCMenu of cocos2d-xna. In game development, it is not enough to use CCSprite and CCScene mentioned above to complete rich interactive behaviors, single interface element operations only increase the complexity of UI development, SO group operations such as CCLayer can provide great convenience for development. This operation experiment is performed on the scenario of level selection to complete complex interactive development.

Clever Use of CCMenuItem

Take out the resource files we have prepared before. In game design, we divide Wei shuwu into several different levels, which requires us to select them separately on the interface, first, let's take a look at the accuracy of image resources. There are several button files in GameUI01.plist:

A highlighted red button is used to indicate selected items, while a highlighted red button can be clicked. On the label header, selected items cannot be clicked. Therefore, you can use the Enabled Attribute combination of CCMenuItem to achieve the effect, open SceneSelect. cs class. modify the original code in the place where the Tab button is created in the constructor. The original code is to use CCSpirte to paste a display chart. For details, see the previous one,

First, create a member of the class:

CCMenu story_tabs;

CCMenu story_tabs can be used in a short time. The following constructor will write the following code:

// The above Tab button creates CCMenuItemSprite tab1 = CCMenuItemSprite. itemFromNormalSprite (CCSprite. spriteWithSpriteFrameName ("tab_shu2.png"), CCSprite. spriteWithSpriteFrameName ("tab_shu1.png"), CCSprite. spriteWithSpriteFrameName ("tab_shu1.png"), this, click_story_tab); CCMenuItemSprite tab2 = CCMenuItemSprite. itemFromNormalSprite (CCSprite. spriteWithSpriteFrameName ("tab_wu2.png"), CCSprite. spriteWithSpriteFrameName ("tab_wu1.png"), CCSprite. spriteWithSpriteFrameName ("tab_wu1.png"), this, click_story_tab); CCMenuItemSprite tab3 = CCMenuItemSprite. itemFromNormalSprite (CCSprite. spriteWithSpriteFrameName ("tab_wei2.png"), CCSprite. spriteWithSpriteFrameName ("tab_wei1.png"), CCSprite. spriteWithSpriteFrameName ("tab_wei1.png"), this, click_story_tab); story_tabs = CCMenu. menuWithItems (tab1, tab2, tab3); // splits story_tabs.alignItemsHorizontallyWithPadding (10) at intervals of 10 pixels in the horizontal direction; // converts it to the coordinates of story_tabs.position = CCDirector. shareddire (). convertToUI (new CCPoint (300, 72); // set the first one to tab1.Enabled = false; this. addChild (story_tabs );

This Code creates several buttons and combines them into a CCMenu. It is worth noting that CCDirector. shareddire (). convertToUI () method. This method converts coordinates into UI coordinates. You must know that the coordinates in cocos2d are in the lower left corner and up, rather than in the upper left corner. This method can be used for convenient conversion.

Currently, it cannot be run because the click_story_tab method is not implemented. The implementation method in this class is as follows:

Private void click_story_tab (CCObject sender) {// traverse story_tabs foreach (var item in story_tabs.children) {// determine whether it is CCMenuItem. If yes, all Settings except sender are set to true if (item is CCMenuItem) (item as CCMenuItem ). enabled = item! = Sender ;}}

It may not seem easy to understand at the beginning. In fact, let's just make a logical judgment here. The if else implementation is like this:

if(item != sender)    (item as CCMenuItem).Enabled = false;else    (item as CCMenuItem).Enabled = true;

You can use any method. Run it now to see the effect.

When you click any tag, the status will be activated, and you cannot click it at this time. Now, we need to consider how to implement the corresponding level content.

CCLayer

In the code in the previous article, I just used the for loop to draw a few buttons and then let the button trigger the jump scenario. Obviously, now with the classification tab, the corresponding levels below also need to be changed, if you use a very rough method (each group writes a button separately, whether it can be viewed or managed), it is not only troublesome to manage, but also inconvenient to control the animation, next we will use the CCLayer layer Layer to put these buttons together. The concept of the layer should be easy to understand if you have played PS. The following figure is a brief description:

Different labels of Wei shuwu correspond to a different layer. When a pair is clicked, the layer changes. Therefore, we abstract the layer class code of a level as follows:

Public class LayerLevels: CCLayer {public LayerLevels () {// level selection layer CCPoint offset = new CCPoint (170,180); for (int I = 0; I <4; I ++) {for (int j = 0; j <3; j ++) {// The level button CCMenuItemSprite level = CCMenuItemSprite. itemFromNormalSprite (CCSprite. spriteWithSpriteFrameName ("btn_level1.png"), CCSprite. spriteWithSpriteFrameName ("btn_level2.png"), this, click_level); CCMenu menu = CCMenu. menuWithItems (level); // The position is relative to the menu on the top left UI. position = CCDirector. shareddire (). convertToUI (new CCPoint (offset. x + 160 * I, offset. y + 85 * j); this. addChild (menu); // create a MenuItem as the text content CCMenuItem menuitem = new CCMenuItem (); // specify the font description of Arial to ensure that there is Arial in fonts. spritefont var text = CCLabelTTF. labelWithString (j * 4 + I + 1 ). toString (), "Arial", 12); // specify the color as black text. color = new ccColor3B (); menuitem. addChild (text); menu. addChild (menuitem) ;}} private void click_level (CCObject sender) {// when the level is clicked, it will automatically jump to the game scenario CCDirector. shareddire (). pushScene (GameRoot. pSceneGame);} public void Show () {this. visible = true;} public void Hide () {this. visible = false ;}}

Now, return to SceneSelect. cs and remove all the previous buttons for loop. You only need a line of code:

this.addChild(new LayerLevels());

Run the following command:

With a level, a layer display, and a level name, you can use it here to customize the level name in the future, but remember that Chinese characters cannot be displayed, this requires another Chinese Character solution. Let's talk about it later.

For better and future expansion, I added the Show () and Hide () methods to control whether to display them. We will use them now.

However, if you click the corresponding Wei shuwu button, you cannot switch the page. Next, we will consider how to switch the page, map the tags, and create a dictionary:

Dictionary<CCMenuItem, LayerLevels> dictLayerLevels = new Dictionary<CCMenuItem, LayerLevels>();LayerLevels currentlayerlevers = null;

In the SceneSelect constructor:

// Add the test layer // this. addChild (new LayerLevels (); // maps tags to dictLayerLevels in different LyerLevers classes. add (tab1, new LayerLevels () {visible = false}); dictLayerLevels. add (tab2, new LayerLevels () {visible = false}); dictLayerLevels. add (tab3, new LayerLevels () {visible = false}); // display tab1 as the current level layer showLayerLevels (dictLayerLevels [tab1]); // traverse and add it to foreach (var item in dictLayerLevels. values) {this. addChild (item );}

Note that it is useless to comment out the previous one. Then, implement the showLayerLevels method and add the code to the tag click event to make it look like this:

Private void click_story_tab (CCObject sender) {// traverse story_tabs foreach (var item in story_tabs.children) {// determine whether it is CCMenuItem. If yes, all Settings except sender are set to true if (item is CCMenuItem) (item as CCMenuItem ). enabled = item! = Sender;} showLayerLevels (dictLayerLevels [sender as CCMenuItem]);} private void showLayerLevels (LayerLevels layer) {if (currentlayerlevers! = Null) currentlayerlevers. Hide (); layer. Show (); currentlayerlevers = layer ;}

ShowLayerLevels can ensure that the previous level layer is hidden and new ones are displayed.

However, it is useless to click the label above, because there is no change, but it is visible and invisible. To make it clearer, we will use CCAction to achieve the animation effect.

CCMoveTo

CCMoveTo is very simple. It allows an element to move from its current position to a specified new position. Its static method can generate a moving CCAction through time and coordinates, next we will use it to realize the movement and change of the layer, so that when the label is switched, the corresponding change can be seen directly. Open the LayerLevels class and modify the Show method as follows:

Public void Show () {// display it this. visible = true; // set the position to the rightmost out of the screen. this. position = new CCPoint (CCDirector. shareddire (). getWinSize (). width, 0); // specify to move to 0, 0, and CCMoveTo move = CCMoveTo. actionWithDuration (0.5f, new CCPoint (0, 0); // run this Action this. runAction (move );}

Okay. Run it. Have you seen the sliding effect? This effect, of course, cannot be controlled by gestures. You can only click Wei shuwu.

Further, we can see that this effect is still a bit awkward, that is, the previous page disappears directly. Can we move it with a sliding Scroll? Here we need another action to implement the CCSequence queue behavior, the queue behavior is described in detail in the previous article:

Cocos2d-x for WindowsPhone: Develop a hamster game (below ):

We will use this Action to implement the Hide method. After the hidden animation is completed, this layer will be hidden, the Hide method will be transformed, and the callback method will be added:

Public void Hide () {// specifies to move to the leftmost and beyond the screen CCMoveTo move = CCMoveTo. actionWithDuration (0.5f, new CCPoint (-CCDirector. shareddire (). getWinSize (). width, 0); // executes a queue action. After the movement is completed, HideAniCompled this is called. runAction (CCSequence. actionOneTwo (move, CCCallFunc. actionWithTarget (this, HideAniCompled);} void HideAniCompled () {this. visible = false ;}

Run the following command again:

When you click the corresponding tag, it will change. Is interaction enriched immediately? Now, you can try to make full use of your imagination.

This article focuses on Interactive Development of CCLayer and CCAction in combination to achieve the scenario of level selection. There are not many other considerations. In formal development, the level selection interface is closely related to the level design, the construction and design of corresponding data are crucial. This part is completed step by step later.

There are a lot of methods about Action, interested friends can refer to the test project sample in the cocos2d-xna of OpenXLive transplantation, which shows a lot of behavior effects, such as shrinkage, shear, opacity, etc, there will be no more explanations here.

This example project: https://github.com/Nowpaper/SanguoCommander_cocos2dxna_Sample
In this example, the project name is SanguoCommander4.

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.