Use spritesheet in the cocos2d-x and create an animation with spritesheet

Source: Internet
Author: User

This tutorial describes the advantages of spritesheet (the spritesheet chart mainly uses CCSpriteBatchNode) and how to use spritesheet to create an animation.

The reference articles of this tutorial are: himi blog articles about CCSpriteBatchNode, http://blog.csdn.net/xiaominghimi/article/details/6761811

Http://www.cnblogs.com/zilongshanren/archive/2011/04/11/2012770.html ()

If you do not know about cocos2d-x programming, You can first read the "using cocos2d-x to make a simple windows phone 7 game" series of articles. However, if you have relevant experience, you should leave it alone.

If you have never used spritesheet, you can think of it as a huge image, and you can put a lot of sprite in it. Corresponding to spritesheet, there is also a plist file, which specifies the position and size of each independent sprite in this "big image, when you need to use this sprite between codes, you can easily use this information in the plist file to obtain the sprite.

Using CCSpriteBatchNode to get the genie in spritesheet can improve efficiency.

Why does this increase efficiency? Because the cocos2d-x has optimized it! If you use spritesheet to obtain sprite, when there are many sprite in the scenario, if these sprite share a spritesheet, although there is no OpenGL ES in XNA, the rendering method is similar, XNA-based games can execute multiple graphic and text words between the Begin Method for calling a spriteBatch object and the End Method for calling a spriteBatch object, the XNA Framework displays the content of multiple images in batches at a time. The cocos2d-x will use a spriteBatch call to draw these sprite. However, if it is a single sprite, there will be N spriteBatch calls, which is quite expensive. The optimization is to reduce the call to the spriteBatch Begin and End methods.

In short -- using spritesheet will be faster, especially when you have a lot of sprite!

Zwoptex To viceless!

Although plist is a file, it is quite troublesome to manually use the image editor to edit the image and then edit the plist file. Here we use a free tool, Zwoptex. I use the flash version, and the installation version is the paid version. After all, we just edit an image, and the flash version is enough.

First, download the images required for this tutorial. The images used are the pictures of ray, the original author of the article translated by Zilong Mountain, and the main reason is that my drawing level is really good, PS is the level of use, ah, there is no artist day)

Download Zwoptex, Kernel. After downloading the file, decompress it and open zwoptex.html.

Then you can start creating spritesheet. Click file/Import images, select all eight bear images, and click open to add them to the project. You will find that all the images overlap. We don't need such a large image now. click Modify/canvas width and select 512px. This is enough, and then click array/by name & height, at this time, it is found that the bear is in every two rows, a total of four rows. At this time, the editing of the image is complete. Then export it. Click file/export texture.save as animbear.png. Then click File/export coordinates. Save as animbear. plist.

 

Let the bear get started

Now open vs2010, create a new cocos2d-x project named cocos2dbearrundemo, the same, openxlive plug-in is not needed. Like previous projects, it is necessary to fix DLL references. Because this example is relatively simple, it is directly modified in helloworldscene. In this case, clear the init method in helloworldscene.

Dimensions is added to resource/images, and animbear. plist is added to the resource folder. Then select the animbear. plist file in solution manager. Select properties. Modify contentimporter and contentprocessor as follows:

 

If you cannot see these two options, check the reference of content and make sure that the reference of cocos2d. content. pipeline. Importers is not displayed as an exclamation point. If yes, remove it and add it again.

Then open the animbear. plist file. Delete the row in the red box below and save it.

Why delete this line, because the xNa version of The cocos2d-x is using XML parsing method, this line can not be skipped, will report an error. Therefore, you can directly delete it.

Open the helloworldscene file. Start real animation production. The following are all modified in init.

Five steps are required to obtain the animation effect. Next, we will explain one step at a time.

 1) buffer sprite frames and textures

  

 CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFramesWithFile(@"resource/AnimBear");

First, call the addspriteframecache addspriteframeswithfile method of ccspriteframecache and pass the plist file generated by zwoptex as a parameter. This method does the following:

  • Find an image file suffixed with .png in the project directory and the input project name. Then add the file to the shared cctexturecache. The hosts file is stored in the directory at the next level .)
  • Parse the plist file, track the positions of all Sprite in spritesheet, and use the ccspriteframe object internally to track the information.

2) create a batch processing node

            CCSpriteBatchNode spritesheet = CCSpriteBatchNode.batchNodeWithFile(@"resource/images/AnimBear");            this.addChild(spritesheet);

Next, create the ccspritebatchnode object and pass the spritesheet as a parameter. The working principle of spritesheet in cocos2d is as follows:

  • You create a ccspritebatchnode object, pass the name of a spritesheet containing all Sprite as a parameter, and add it to the current scenario.
  • Next, you should add any sprite you created from spritesheet as a child of ccspritebatchnode. As long as the Sprite is included in the spritesheet, no problem occurs. Otherwise, an error occurs.
  • CCSpriteBatchNode intelligently traverses all of its child nodes and renders these children through a spriteBatch call, instead of requiring a spriteBatch call for each sprite in the past, rendering will be faster.

3) List of collected Frames

            List<CCSpriteFrame> walkAnimFrames = new List<CCSpriteFrame>();            for (int i = 1; i <= 8; i++)            {                walkAnimFrames.Add(CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName(String.Format("bear{0}.png", i)));            }

To create a series of animated frames, we simply repeat our image names (named by bear1.png> bear8.png) and use the shared ccspriteframecache to get each animation frame. Remember, they are already in the cache, because we previously called the addspriteframeswithfile method.

4) Create an animation object

            CCAnimation animation = CCAnimation.animationWithFrames(walkAnimFrames, 0.1f);

Next, we will create a ccanimation object by passing in the sprite frame list and specify the animation playback speed. We use 0.1 to specify the interval between each animation frame.

5) create a sprite and let it run the animated action

            CCSize winSize = CCDirector.sharedDirector().getWinSize();
       CCSprite bear = CCSprite.spriteWithSpriteFrameName(@"bear1.png"); bear.position = new CCPoint(winSize.width / 2, winSize.height / 2); var walkAction = CCRepeatForever.actionWithAction(CCAnimate.actionWithAnimation(animation, false)); bear.runAction(walkAction); spritesheet.addChild(bear);

We first create a sprite through spriteframe and place it in the middle of the screen. Then, generate the CCAnimationAction, assign the value to the intent action attribute of the scenario, and finally let the bear run the action.

Finally, we add the bear to the spritesheet scenario -- add it as a child of spritesheet. Note: if we do not add it to spritsheet, but to the current layer. We will not be able to get the performance improvement that spritesheet brings to us !!!

Finished!

In addition, since we only have one scenario, we need to add a label to make the sprite background transparent, it is unclear why. Add one.

            CCLabelTTF label = CCLabelTTF.labelWithString("Bear walk", "Arial", 32);            label.position = new CCPoint(winSize.width / 2, winSize.height - 80);            this.addChild(label);

Now, we can see that the bear is leaving.

So how can we turn the bear? Set the bear property bear. isflipx = true; that is, the X axis flip. This will make the bear flip over. Of course, it can also be flipped vertically.

Note:

Although ccspritebathnode can be optimized, note the following:

When initializing the ccspritebatchnode set, an image resource (or PVR file) will be loaded. Therefore, the child genie that restricts the set must use the image loaded by the set, otherwise, a warning is given;

Note that when using ccspritebatchnode, because the genie are stored in the collection, the node (genie) in the ccspritebatchnode of this set will be on the same Z axis and in the same depth;

This tutorial ends. Sample Code download: http://dl.dbank.com/c04ey6mse6

 

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.