This article practice from Ray wenderlich, Tony dahbura article "How to Use animations and sprite sheets in cocos2d 2.x", the use of cocos2d, I am here to use Cocos2D-x 2.1.4 for learning and transplantation. In this article, we will learn how to create a simple bear walking animation, how to use the genie form, and how to change the direction of the bear walking.
The procedure is as follows:
1. New Cocos2d-win32 project named "animbear ";
2. Download resources required for this game;
The size of these images is the size required for the maximum resolution and will be used to create the sizes required for different resolutions.
3. Download
Texture packerTool. The current version is 3.1.2. Drag the resource image file to the right window of texture packer to automatically load the file. In the left-side window, adjust the geometry panel and Max
The size is 4096x4096, because the default size is not enough. Layout panel, set trim mode to none, do not need to remove transparent pixels. After completion, as shown in:
In"
Resources"Create a folder under the directory"
HDR". Check whether cocos2d and data are selected for data format in the output panel.
Locate filename"
... \ Animbear \ resources \ HDR"Path, file name:
Animbear. plist. After saving, texture file will automatically fill in the file name. Then, click the autosd Settings button, drop-down select presets item as cocos2d-x
"HDR/HD/sd", click "Apply", which enables you to automatically create and save genie forms with multiple rules at the time of release, as shown in:
Finally, click "publish" on the toolbar to automatically generate the sprite form and texture file, as shown in:
Available
Plist editor proOpen
Animbear. plistFile. It consists of two parts: frame and metadata. In the frame section, each image has an attribute used to describe the Package Box in the genie form. As shown in:
3. A simple animation. Open
Helloworldscene. hFile, add the following code:
1 2 3 4 5 6 |
|
Cc_synthesize_retain (cocos2d: ccsprite *, _ bear, bear ); Cc_synthesize_retain (cocos2d: ccaction *, _ your action, your action ); Cc_synthesize_retain (cocos2d: ccaction *, _ moveaction, moveaction );PRIVATE: Bool _ bearmoving; |
Open
Helloworldscene. cppFile. In the constructor, add the following code:
1 2 3 4 5 6 7 |
|
Helloworld: helloworld () { _ Bear = NULL; _ Required action = NULL; _ Moveaction = NULL; _ Bearmoving = false; } |
Modify
InitFunction, as shown in the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
Bool helloworld: Init () { Bool Bret = false; Do { Cc_break_if (! Cclayer: Init ());
// 1) cache the sprite frames and Texture Ccspriteframecache: sharedspriteframecache ()-> addspriteframeswithfile ("animbear. plist ");// 2) create a Sprite batch Node Ccspritebatchnode * spritesheet = ccspritebatchnode: Create ("animbear.png "); This-> addchild (spritesheet ); // 3) Gather the list of frames Ccarray * walkanimframes = ccarray: Create (); For (INT I = 1; I <= 8; ++ I) { Walkanimframes-> addobject (ccspriteframecache: sharedspriteframecache ()-> spriteframebyname ( Ccstring: createwithformat ("bear#d.png", I)-> getcstring ())); }
// 4) Create the animation object Ccanimation * walkanim = ccanimation: createwithspriteframes (walkanimframes, 0.1f ); // 5) Create the sprite and run the animation action Ccsize winsize = ccdirector: shareddirector ()-> getwinsize (); This-> setbear (ccsprite: createwithspriteframename ("bear1.png ")); This-> getbear ()-> setposition (CCP (winsize. width/2, winsize. Height/2 )); This-> setmediaaction (ccrepeatforever: Create (ccanimate: Create (walkanim ))); This-> getbear ()-> runaction (this-> getmediaaction ()); Spritesheet-> addchild (this-> getbear ()); Bret = true; } While (0 ); Return Bret; } |
The preceding steps are described as follows:
①. Cache the sprite frames and textures. Call the addspriteframecache addspriteframeswithfile method of ccspriteframecache and pass in the name of the previously generated attribute list file. This method does the following:
- Extract the value of texturefilenamefrom the metadata of the source file, and set it to the file name of the texture file. Here it is animbear.png, and load the file to the cctexturecache texture cache. Note that the correct file is automatically searched based on the specified resource search path.
- Parse the attribute list file and use the ccspriteframe object to internally track information of all genie.
2. Create a batch processing node. Create a ccspritebatchnode object and input the sprite form image name. The sprite form works as follows:
- Create a ccspritebatchnode object, input the name of the image file containing all the genie, and add the object to the scenario.
- Now, any time you create an genie from this genie form, you should add this genie to this ccspritebatchnode object. As long as the genie is from this genie form, it will work normally; otherwise, an error will be reported.
- The ccspritebatchnode code intelligently draws a ccsprite child object in one OpenGL ES call, rather than multiple calls, which makes the call much faster.
③. List of captured frames. To create a frame, simply retrieve the image name (bear1.png> bear8.png, which is a Convention) and then search for the sprite frame with the specified name from ccspriteframecache. Remember, these should already be in the cache, because the addspriteframeswithfile method was previously called.
4. Create an animation object. Create a ccanimation object and specify the playback speed of the animation by passing in the sprite frame list. 0.1 seconds is used as the latency between frames.
⑤. Create Genie and run animated actions. Create a genie (that is, a bear) with a frame and place it in the center of the screen. Input the ccanimation object, create the ccanimate object, and let the bear run this action. Finally, add the bear to the genie form. Note: if it is not added to the sprite form but to the layer, the performance will not be optimized.
To load different resources at different resolutions, you must first set resolution adaptation to enableAppdelegate. cppFile, inApplicationdidfinishlaunchingIn the function, the code above is changed:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
// Initialize Director Ccdirector * pdirector = ccdirector: shareddire (); Pdirector-> setopenglview (cceglview: Export dopenglview ());Ccsize screensize = cceglview: Export dopenglview ()-> getframesize (); Ccsize designsize = ccsizemake (480,320 ); Cceglview: Export dopenglview ()-> setdesignresolutionsize (designsize. Width, designsize. Height, kresolutionnoborder ); Ccsize framesize = cceglview: Export dopenglview ()-> getframesize (); Ccsize resourcesize; STD: vector <STD: String> searchpath; If (framesize. Height> 768) { Searchpath. push_back ("HDR "); Resourcesize = ccsizemake (2048,153 6 ); } Else if (framesize. Height> 320) { Searchpath. push_back ("HD "); Resourcesize = ccsizemake (1024,768 ); } Else { Searchpath. push_back ("SD "); Resourcesize = ccsizemake (480,320 ); } Pdirector-> setcontentscalefactor (resourcesize. Height/designsize. Height ); Ccfileutils: sharedfileutils ()-> setsearchpaths (searchpath ); |
Compile and run the program. You can see the bear walking happily on the screen, as shown in:
4. change the direction of the bear walk. Touch the screen to control the movement of the bear. Open
Helloworldscene. cppFile, in
InitIn the function, comment out the code this-> getbear ()-> runaction (this-> getmediaaction (); so that the bear will not move at the beginning. Add the following code at the end of the Code:
1 |
|
This-> settouchenabled (true ); |
Add the following method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
|
Void helloworld: registerwithtouchdispatcher () { Ccdirector: shareddirector ()-> gettouchdispatcher ()-> addtargeteddelegate (this, 0, true ); }Bool helloworld: cctouchbegan (cctouch * ptouch, ccevent * pevent) { Return true; } Void helloworld: cctouchended (cctouch * ptouch, ccevent * pevent) { // 1) determine the Touch Location Ccpoint touchlocation = This-> converttouchtonodespace (ptouch ); // 2) set the desired velocity Ccsize screensize = ccdirector: shareddirector ()-> getwinsize (); Float bearvelocity = screensize. width/3.0f; // 3) figure out the amount moved in X and Y Ccpoint movedifference = ccpsub (touchlocation, this-> getbear ()-> getposition ()); // 4) figure out the actual length moved Float distancetomove = ccplength (movedifference ); // 5) figure out how long it will take to move Float moveduration = distancetomove/bearvelocity; // 6) flip the animation if necessary If (movedifference. x <0) { This-> getbear ()-> setflipx (false ); } Else { This-> getbear ()-> setflipx (true ); }
// 7) run the appropriate actions This-> getbear ()-> stopaction (this-> getmoveaction ()); If (! _ Bearmoving) { This-> getbear ()-> runaction (this-> getmediaaction ()); }
This-> setmoveaction (ccsequence: Create ( Ccmoveto: Create (moveduration, touchlocation ), Cccallfunc: Create (this, callfunc_selector (helloworld: bearmoveended )), Null )); This-> getbear ()-> runaction (this-> getmoveaction ()); _ Bearmoving = true; } Void helloworld: cleanup () { Cc_safe_release_null (_ moveaction ); Cclayer: cleanup (); } Void helloworld: bearmoveended () { This-> getbear ()-> stopaction (this-> getmediaaction ()); _ Bearmoving = false; } |
When
BearmoveendedWhen the method is called, it is no longer moved and the animation is stopped.
CctouchendedThe method is described as follows:
- ① Determine the touch position. Convert the coordinates of the touch point to the local node.
- ② Set the expected speed. Set the moving speed of the bear.
- ③ Calculate the moving distance between the X axis and the Y axis.
- ④ Calculate the actual length of the movement.
- ⑤ Time required to calculate the movement.
- ⑥ If necessary, flip the animation. Determine whether the bear moves to the left or right by moving the X axis of the distance. You only need to set the horizontal flip, and the running animation will also flip.
- 7. Run appropriate actions. First, stop the existing movement because it may change the bear's destination halfway. Then, if you are already moving, keep walking. Finally, create a mobile action, specify the location, time, and call back when the action is completed. This callback is used to stop the walking action. Variable _ bearmoving is used to determine whether the object is being moved.
Compile and run, and touch the screen to move the bear, as shown in:
References:1. http://www.raywenderlich.com/32045/how-to-use-animations-and-sprite-sheets-in-cocos2d-2-x2.http://www.codeandweb.com/texturepacker/documentation
Thank you very much for the above materials. In this example, additional resources are added to the source code.: Http://download.csdn.net/detail/akof1314/5914987
If there is an error in the article, please point it out for correction.