WP7 game development: tweejump (cocos2d-xna)

Source: Internet
Author: User

Tweejump

This tutorial briefly describes how to use Cocos2d-XNA to make a simple WP7 game. You can follow the tutorial step by step, or simply jump to the end of the article and download simplegame.

Download and install the Cocos2d-XNA
  1. You can download Cocos2d-XNA source files from the following link

Https://github.com/cocos2d/cocos2d-x-for-xna

Cocos2d-XNA main file role:

Install-template-mscs.msi: Template Installer

Cocos2d-xna: main projects

Cocosdenshion: Sound Effects

Cocos2d. Framework, cocos2d. content. pipeline. Importers: supports text resources (*. fnt, *. tmx, *. plist)

Hellococos2d: Sample project

Tests: function demonstration

 

  1. Install Template

 

Next next... complete the installation. If a User Account Control prompt appears, select "Next" and continue the installation.

Then you can create a cocos2d-xna project.

 

Hello, Cocos2D-XNA!

Start cocos2d-xna.sln add new project select Cocos2d-xna application under xNa game studio 4.0 node, give the project name tweejump.

 

After OK, a dialog box is displayed.

 

Let's make sure that we can choose OK (openxlive is a game competition and social network SNS platform on Windows Phone 7, allows developers to add the game competitive service and social network SNS features for their games with minimal workload. Openxlive is developed and operated by FULCRUM Mobile Networks, Inc. Similar applications include openfeint and plus + on the iPhone .) Www.openxlive.com

 

We set the created Project as a startup Item, for example:

 

F5 run, Cocos2D-XNA helloworld program, start the simulator, the program running interface is as follows:

 

By default, there is only one scenario helloworldscene in the project, except for the hall, points, achievements, and sample code hellococos2d.

Cocos2d is organized according to the concept of scene, and the game is switched by multiple scene. A game scenario generally refers to a part that can run independently at a certain time point, including visible game roles, terrain, and invisible logic scripts. For example, a specific level of a game, game menus, and field animations are all independent scenes. Scenes in cocos2d are composed of different layers. Tweejump requires three scene, namely the main menu, game screen, and game ending screen (gameover), to complete our game logic. The game process is as follows: choose game> main menu play> game screen start game> game end call gameover screen> again> game screen.

 

Cocos2d-XNA Basics

The following describes the main Cocos2d-XNA classes used in tweejump.

Ccdirector is responsible for managing scenarios and switching scenarios.

Ccnode is the most important object in the Cocos2d-XNA. The addchild () method of ccnode is the most important method in my opinion. It acts as a container and can add child to countless nodes, but each node has only one parent node. At the same time, it can execute callback functions and ccaction with attributes such as postion, scale, and rotation.

Cclayer, a subclass of ccnode, and a layer is a area that can be drawn. You can add objects such as UI and sprite to it.

Ccmenu is derived from cclayer and can process input messages. ccmenu contains multiple ccmenuitem objects. After receiving the input message, the input message is distributed to the corresponding menuitem according to the touch position, run the callback function. ccmenu also provides an alignment menu item function.

Ccsprite can be viewed as a cutting part of a 2D image at a certain time point.

Add background for our game

In the tweejump game, the background is blue sky and white clouds. In order to reuse it, we extract it into the parent class main. The main menu mainmenu, the game screen game, and the ending screen gameover will inherit it as long as it inherits the blue sky and white clouds.

Paint and draw out the cute blue sky and white clouds in Main. In order to facilitate the management of the classes used in the game, try to build them into the classes folder and create the class main:

 

Let main inherit the cclayer and override the init () method

Public class main: cclayer

{

// Adjust the proportion of Materials

Public const float Sy = 1.666666666666667f;

Public const float SX = 1.5f;

Public static void Scale (ccnode sprite)

{

Sprite. scaley = sy;

Sprite. scalex = SX;

}

 

Public override bool Init ()

{

If (! Base. INIT ())

{

Return false;

}

// @ Todo

Return true;

}

}

First, paste the blue sky to @ todo:

Ccspritebatchnodespritemanager = ccspritebatchnode. batchnodewithfile("Images/Sprites",10);

Addchild(Spritemanager,-1,(Int)Tags. kspritemanager);

Ccspritebackground = ccsprite. spritewithtexture(Spritemanager. Texture,Newccrect(0,0,320,480));

Spritemanager. addchild(Background);

Scale(Background);

Background. Position = newccpoint(240,400);

//This. initclouds();Initialize cloud

//This. Schedule(Step);Make the cloud more attractive

 

Place the tags enumeration outside the class

Public Enum tags

{

Kspritemanager = 0,

Kbird,

Kscorelabel,

Kcloudsstarttag = 100, // The value indicates that a segment is separated.

Kplatformsstarttag= 200,

Kbonusstarttag= 300

}

 

Although only blue sky is added, let's take a look at the effect first. You need to modify the entry point of scene before running. In

In appdelegate. CS, locate the following code in the applicationdidfinishlaunching () method and modify it:

// Create a scene. It's an autorelease object

Ccscene pscene = tweejumpscene. Scene ();

// Run

Pdirector. runwithscene (pscene );

 

Now we need to instantiate pscene as our main, but the bad thing is that our main. CS is a cclayer and not ccscene. The implementation code is as follows:

Ccscene pscene = ccscene. node ();

Pscene. addchild (tweejump. classes. mainmenu. node ());

 

In Main. CS, you also need to add the node () method to call the init () method to complete initialization.

Publicstaticnewcclayernode()

{

Mainret = newmain();

If(Ret. init())

{

Returnret;

}

Returnnull;

}

 

It's ugly to run F5.

 

Because the screen is a landscape screen by default in the game, you need to add this sentence in applicationdidfinishlaunching () to set the screen to a portrait screen:

 

Pdirector. deviceorientation = ccdeviceorientation. ccdeviceorientationportrait;

 

Blue sky texture OK, undo our comments, remove text instructions, and then paint the cloud on the main background.

Directly paste the Code a little longer. In order to appear technically less sensitive, view the source code in detail (cocos2d is easy to use ).

Privatevoidinitclouds()

{

Currentcloudtag =(Int)Tags. kcloudsstarttag;

While(Currentcloudtag <(Int)Tags. kcloudsstarttag + knumclouds)

{

This. initcloud();

Currentcloudtag ++;

}

This. resetclouds();

}

The initclouds () method completes cloud initialization. initclouds () calls knumclouds = 12 times. initcloud () This Method Randomly outputs blocks from three clouds, and then calls resetclouds () complete cloud location initialization. For details, refer to the source file.

Main. CS registers spritemanager and adds it to the cclayer (addchild () method of main). It retrieves spritemanager as needed. A part of texture is saved to ccsprite to form a new ccsprite object, and then spritemanager. addchild (ccsprite :) is handed over to spritemanage for unified management.

Use spritemanager. getchildbytag (TAG :) retrieves the corresponding Sprite and assigns the position value to achieve the required texture, movement, action, and so on (position is the position of the image center ); therefore, it is very convenient to specify a unique and regular tag for each sprite (the function of enumerating tags ).

Use getchildbytag to traverse the required Sprite in spritemanager and assign values to view the source code resetxxxx () method. Not only does main. CS exist, but you can also find the initxxxx () resetxxxx () method in game.

Source code Solution Explorer:

 

 

Main Menu and end screen

Skip... Skipped... Main. CS is over. Let's take a look at the use of menus and labels, you can use them to easily complete tweejump or the main menu and gameover of your own game (If your game is not very complex ).

Mainmenu. CS and gameover. CS both inherit from Main. CS because Dad is Li Gang and has the background of blue sky and white clouds. With the addition of menu, Labe, and Sprite, let's take a look at how simple it is.

Repeat the preceding steps to override Init () and add the node () method. paste the following code in Init ().

Ccmenuitem button1 = ccmenuitemimage. itemfromnormalimage (@ "Images \ loginbutton", @ "Images \ loginbutton", this, logincallback );

Scale (button1 );

Ccmenuitem button2 = ccmenuitemimage. itemfromnormalimage (@ "Images \ playbutton", @ "Images \ playbutton", this, playcallback );

Scale (button2 );

Ccmenuitem button3 = ccmenuitemimage. itemfromnormalimage (@ "Images \ aboutbutton", @ "Images \ aboutbutton", this, aboutcallback );

Scale (button3 );

Ccmenu menu = ccmenu. menuwithitems (button1, button2, button3 );

Menu. alignitemsverticallywithpadding (15f );

Menu. Position = new ccpoint (240,257 );

This. addchild (menu );

 

Ccmenuitemimage. the first two parameters of itemfromnormalimage () are the image resource (ccsprite) before and after the press, and the last parameter is the callback function after the press, in the format of void callback (ccobject sender ){}. Draw the response of our game's logo completion callback function and replace runwithscene () with mainmenu, as shown below.

 

The final score display in gameover. CS is implemented by cclabelbmfont, which makes your words very personalized and cool. paste the Code:

Cclabelbmfont scorelabel = cclabelbmfont. labelwithstring (currentscore. tostring (),

"Fonts/bitmapfont ");

Scorelabel. scalex = SX * 1.5f;

Scorelabel. scaley = Sy * 1.5f; // The clip is too small to ignore

Addchild (scorelabel, 5, (INT) tags. kscorelabel );

Scorelabel. Position = new ccpoint (240,450 );

 

Gaming, label3961 is a good score.

Bitmapfont is the resource file bitmapfont. fnt. If the content impoter is not set to text importer in the attribute, and the content processor is textprocessor, a compilation error will occur. Open this file and you can see that it is a key value pair connected by equal signs. Focus on char id = 32 48... It represents space 0123456789, And the cursor behind each char IDR shows the space 0123456789 position of this chart on bitmapfont.png.

 

The. fntfile and the corresponding. PNG file have a corresponding location relationship, which must follow and cannot be changed .. The Directory of the fntfile has an imagesfile containing the corresponding. PNG file.

 

Game control-gravity sensing

This version of the cocos2d-xna is not encapsulated gravity sensing, I use xNa self-carried gravity sensing, because accelerometer it is also event-driven so it is very good to do not appear incompatible phenomenon, it should not be encapsulated in later versions.

1 add Microsoft. devices. Sensors reference

 

2. Create an accelerometer object, 3. register the currentvaluechanged event of the accelerometer object, and 4. Start the accelerometer object start () method to start the gravity sensor listener.

In the registered event handling method, you can use E. sensorreading. acceleration. X and E. sensorreading. acceleration. y, E. sensorreading. acceleration. Z to access the 3D offset value of the current acceleration. Here, I only need to mention one. In many tutorials, The readingchanged event of the accelerometer object is registered. When you are using the Windows Phone 7.1 SDK, Vs will prompt you That the readingchanged event is outdated, of course you can use it, but we recommend that you use currentvaluechanged. The timebetweenupdates attribute affects the interval between two triggering currentvaluechanged events. Therefore, if you want to set the interval of gravity sensing, you 'd better use currentvaluechanged. For details, see the init () of the source code game. CS ().

Integrate openxlive SDK

Functions of openxlive:

Rankings

Let the world know that you are the strongest player in this game! The point list is used to record your game performance, so that you can share your extraordinary game performance with players all over the world.

· Game achievements

Game achievements, like a medal, record your growth history in the game. By making achievements, you can tell your friends how you are the best warrior in the game.

· Social Networks

Tell you how many siblings in the world are fighting with you in the game. Find them and become friends with them to start a journey of adventure.

· Personal Center

Here is a story of your past, present, and future. Your points, your achievements, the games you 've played, and your friends are worth your record.

· Cloud storage

Don't you want others to discover your secrets in the game? Put it on the cloud. You can open the dusty secret anywhere.

· Game announcements

Tell you what happened in the game, for example, you became No. 1.

 

If you are in front

Check the openxlive SDK, and add references to the new project to make it easy to use.

Friends familiar with xNa will find that our game engine Cocos2d-XNA is actually a gamecomponent and our openxlive SDK is also a gamecomponent, open our main game class game1 source code called gamemain, is to find the product that inherits from Microsoft. xNa. framework. game class.

Compare our project tweejump with the game1.cs file of the sample program hellococos2d. A few more pieces of code is integrated with openxlive.

Fields in the game1 class

// # Error please full your game secret key in below code

Private string apisecretkey = "y8euf6f5xxegsuw3dkkntbhq ";

Xliveformmanager manager;

 

In the game1 constructor, add the xliveformmanager instance to component.

// Create xlive formmanager

Manager = new xliveformmanager (this, apisecretkey );

Manager. opensession ();

// Add xlive formmanager in components

Components. Add (manager );

 

Note that the add of gamecomponents of openxlive must be placed before the gamecomponents of the game engine of the Cocos2d-xna.

Loads resources in loadcontent () to add background events to the openxlive sdk ui and exit the UI events.

Texture2d background = This. content. Load <texture2d> (@ "Images \ openxlive ");

Manager. Background = background;

Manager. uiexitingevent + = new eventhandler (manager_uiexiting );

 

Void manager_uiexiting (Object sender, eventargs E)

{

Ccdirector. shareddirector (). runningscene. Visible = true;

}

 

If you select openxlive SDK when creating a project, the code is added to game1.cs by default.

 

The following uses mainmenu as an example to teach you how to use openxlive SDK in a game.

Create a button in the init () method

Ccmenuitemimage loby = ccmenuitemimage. itemfromnormalimage (

@ "Images \ lolobby", @ "Images \ lobby1", this,

New sel_menuhandler (lobbycallback ));

Lolobby. Position = new ccpoint (0, 20 );

Ccmenu lmenu = ccmenu. menuwithitems (lolobby );

Lmenu. Position = new ccpoint (240, 60 );

Callback method:

Public Virtual void lobbycallback (ccobject psender)

{

Ccdirector. shareddire(). Pause ();

Ccdirector. shareddirector (). runningscene. Visible = false;

Openxlive. Forms. xliveformfactory. Factory. showform ("lolobby ");

}

 

Openxlive. forms. xliveformfactory. factory. showform ("lolobby"); show the form we need. Here is lolobby, in addition to "loby", "Startup", "leaderboard", "achievements", "Logon", "mycenter", "firendslist", "onlineplayer", "pause", and "openxlivegames".

Tweejump uses three common functions: "achievements", "leaderboard", and "loby. After show is displayed, make sure to hide the current scene when the game is suspended. When you come back, make sure to display the current scene when the game starts.

Void manager_uiexitingevent (Object sender, eventargs E)

{

Ccdirector. shareddirector (). runningscene. Visible = true;

Ccdirector. shareddire(). Resume ();

}

 

Development Resources

Source code

Http://tweejump.codeplex.com/

Website

Http://www.cocos2d-x.org/

QQ Group

190784175

Email

Xnagame@qq.com

Related Article

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.