Cocos2d-x Study Notes (16) -- spritesheet (genie form)

Source: Internet
Author: User

Cocos2d-x Study Notes (16) -- spritesheet (genie form)
Before talking about the content, we need to make some preparations before class;
The sprintf function is defined as follows:
Int sprintf (char * buffer, const char * format [argument] ......);
Usage:
......
Char str [20];
Sprintf (str, "player+d.png", 1 );
.............
The player.png name of this image is copied to the str string. You can directly use str when calling image resources.
Then it is to talk about the inheritance relationship of several classes in the cocos2d-x, to avoid the use of obfuscation in the future:

These two classes are very similar, but there are some functional differences:
CCAnimation is used to load some sprite objects into it. In fact, it is used to put a frame of images together to form a coherent action;
CCAnimate is the CCAnimation Action assigned to the sprite (character role) object.
You can use the following code to describe the two:
[Cpp]
// Animate action
Void ActionAnimate: onEnter ()
{
BasicActions: onEnter ();

CCAnimation * animation = CCAnimation: animation ();
Char frameName [100] = {0 };

For (int I = 1; I <= 5; I ++)
{
Sprintf (frameName, "player+d.png", I );
Animation-> addFrameWithFileName (frameName );
}

CCActionInterval * action = CCAnimate: actionWithDuration (3, animation, false );
M_player-> runAction (action );

}
Last point, because this time is to use spritesheet knowledge, so in advance to introduce a picture editing software Zwoptex, flash: http://zwopple.com/zwoptex/static/downloads/zwoptex-flashversion.zip
With this software, you can easily create a. plist file.
The following describes how to use it:
(1) first, decompress the compressed package. Then, open the zwoptex.html webpage file in the folder. The following page is displayed:

(2) Click "File" and select "import images". Here, I am using spritesheet prepared by others on the internet, http://dl.vmall.com/c0ceul037s. The original link is:
Http://www.raywenderlich.com/1271/how-to-use-animations-and-sprite-sheets-in-cocos2d
Load eight bear images into the project. The first eight images are stacked together, but it doesn't matter. The next step is to expand them. Select the Modify option, select Canvas width, and select 512px,
Then select By Name & Height in the selected Arrange. Finally, 8 images are expanded:

(3) Select the File button, select Export Texture, and name it AnimBea. Select Export Coordinates everywhere. plist file and name it AnimBear. Note that the two must have the same name and the reason will be explained later.
Now, we are entering the code writing stage:
Step 1: Create a cocos2d-x project and name it animation;
Step 2: Here I directly modified the init function code in HelloWorldScene. cpp:
Note: most of the following content references some articles on the Internet. Source:
Bytes
[Cpp]
Bool HelloWorld: init ()
{
//////////////////////////////
// 1. super init first
If (! CCLayer: init ())
{
Return false;
}
 
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// You may modify it.
 
// Add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage * pCloseItem = CCMenuItemImage: itemFromNormalImage (
"CloseNormal.png ",
"CloseSelected.png ",
This,
Menu_selector (HelloWorld: menuCloseCallback ));
PCloseItem-> setPosition (ccp (CCDirector: shareddire()-> getWinSize (). width-20, 20 ));
 
// Create menu, it's an autorelease object
CCMenu * pMenu = CCMenu: menuWithItems (pCloseItem, NULL );
PMenu-> setPosition (CCPointZero );
This-> addChild (pMenu, 1 );
 
 
/*************************************** *********************************/
/* Add animation */
/*************************************** *********************************/
CCSize size = CCDirector: shareddire()-> getWinSize ();
 
 
CCSpriteFrameCache: sharedSpriteFrameCache ()-> addSpriteFramesWithFile ("AnimBear. plist ");
CCSpriteBatchNode * spriteSheet = CCSpriteBatchNode: batchNodeWithFile ("AnimBear.png ");
AddChild (spriteSheet );
 
CCMutableArray <CCSpriteFrame *> * walkAnimFrames = new CCMutableArray <CCSpriteFrame *>;
Char str [20];
For (int I = 1; I <= 8; I ++)
{
Sprintf (str, "bearw.d.png", I );
WalkAnimFrames-> addObject (CCSpriteFrameCache: sharedSpriteFrameCache ()-> spriteFrameByName (str ));
}
CCAnimation * animation = CCAnimation: animationWithFrames (walkAnimFrames, 0.1f );
 
CCSprite * bear = CCSprite: spriteWithSpriteFrameName ("bear1.png ");
// The bear1.png image in this example is the name of the image that is being saved in a slow state, not the bear1.png image in the resourcesfile folder.
Bear-> setPosition (ccp (size. width/2, size. height/2 ));
CCActionInterval * specify action = CCRepeatForever: actionWithAction (CCAnimate: actionWithAnimation (animation, false ));
Bear-> runAction (response action );
SpriteSheet-> addChild (bear );
 
/************* End of adding code *********************/
Return true;
}
(1) buffer sprite frames and textures
CCSpriteFrameCache: sharedSpriteFrameCache ()-> addSpriteFramesWithFile (AnimBear. plist );
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 ("AnimBear.png ");
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
CCMutableArray <CCSpriteFrame *> * walkAnimFrames = new CCMutableArray <CCSpriteFrame *>;
Char str [20];
For (int I = 1; I <= 8; I ++)
{
Sprintf (str, "bearw.d.png", I );
WalkAnimFrames-> addObject (CCSpriteFrameCache: sharedSpriteFrameCache ()-> spriteFrameByName (str ));
}
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 make it run an animation.
CCSprite * bear = CCSprite: spriteWithSpriteFrameName ("bear1.png ");
// The bear1.png image in this example is the name of the image that is being saved in a slow state, not the bear1.png image in the resourcesfile folder.
Bear-> setPosition (ccp (size. width/2, size. height/2 ));
CCActionInterval * specify action = CCRepeatForever: actionWithAction (CCAnimate: actionWithAnimation (animation, false ));
Bear-> runAction (response action );
SpriteSheet-> addChild (bear );
We first create a sprite through spriteframe and place it in the middle of the screen. Then, generate CCAnimationAction, copy it to wlakAction, and finally let the bear run this 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 !!!
Step 3: Compile and run the program. You can see that a bear keeps walking in the center of the screen;

 

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.