"Basic Teaching of COCOS2D-JS (5) Use of resource packaging tools and asynchronous loading processing of resources"

Source: Internet
Author: User
Tags addchild

Texturepacker is a texture resource packaging tool that supports COCOS2DX game resource packaging.

If you have used a classmate can directly see the following resources of the asynchronous loading processing

Why first Use Texturepacker?

1, save the actual size of picture resources

2, reduce the memory load of the large amount of resources in our game

3, easy to play on the memory management of texture resources

Game development to the later stage, we may encounter the bottleneck is the need to "slimming" the game Pack and memory optimization. Then use Texturepacker

will be able to achieve our goal;

We take an example of a set of skill effects images to package Texturepacker pictures and then use them in the program:

We package these files into a large picture.. plist files that are used in PNG and COCOS2DX-JS

Packing note the points:

1, file format, select Cocos2d

2. Set the plist and PNG paths for the exported file

3, picture format, generally use RGBA8888, but according to platform requirements can now also export PVR format picture type;

Using:1) textuer format select PVR Picture type 2) image format Select PVRCT4 this type;

Can greatly save the size of the picture!

4, the PNG size of each large picture must not be greater than 2048*2048! Because the relatively low-end Android phone is not supported to load such a large picture!

So our game to be suitable for most models, it is best not to use too big picture package

Ok. After we have finished packing the files into our Gofinght directory, continue our previous section of knowledge to start writing our code for this section of knowledge:

We need to implement the loading of picture Resources! This is our goal.

Then we need to write a gameframecache.js class to handle the loading of our image resources separately;

Gameframecache.js:

/** * Created by Yangshengjiepro on 15/5/11.*//** * Game resource loading processing*/varGameframecache =function () {     This. Flag = 0;}varLoadingbarproallnum=0;//Asynchronous loadingGameframecache.setallcache =function(obj,objcallback) {//load all game resources asynchronously    varTexcache =Cc.texturecache; //Traverse all the resources    varReslist =Res; varAllnum = 0;  for(varKey = 0inchreslist) {MLOG.C ("Reslist Key" +key+ "value:" +Reslist[key]); Allnum++; } loadingbarproallnum=Allnum; MLOG.C ("Loadingbarproallnum>>", Loadingbarproallnum); varReadnum = 0;  for(varKey = 0inchreslist) {        //Start loadingTexcache.addimageasync (Reslist[key], objcallback, obj); }};//Resource LoadingGameframecache.setcache =function(plist) {if(Jsb.fileUtils.isFileExist (plist) = =true) {cc.    Spriteframecache.getinstance (). Addspriteframes (plist); }    Else{mlog.c ("No Add file>>", plist); }};//Get FrameGameframecache.getcache =function(name) {varframe; Frame=cc.    Spriteframecache.getinstance (). Getspriteframe (name); returnframe;};//Remove PlistGameframecache.removecache =function(plist) {if(Jsb.fileUtils.isFileExist (plist) = =true) {cc.    Spriteframecache.getinstance (). Removespriteframesfromfile (plist); }}
View Code

There are three methods in the code:

As the name implies, add, get, and delete

Add a large-picture resource method:

Cc. Spriteframecache.getinstance (). Addspriteframes (plist);

We know that Spriteframecache can help us preload plist images and greatly improve the rendering efficiency of our games for images.

So we use this way as much as possible to do the image rendering, and we can more convenient, in the right place to add, get, delete;

In order to achieve our best memory resources management way! will not cause us to load too many pictures cause the program is inefficient or even stuck!

So let's use the Spriteframecache class, we need to add a method to the base class in our last lesson

Setgameframecache:function(plistfile) {     gameframecache.setcache (plistfile);},

Very simple, is to call our Gameframecache set Method!

Add the calling method in our Mainlayer, directly:

this. Setgameframecache ("plist file path");

You can call the load map method to our base class!

And then we try to call our big picture textures using, we create a new Pfuns.js action class to play our skill effects!

Pfun.js

/** * Created by Yangshengjiepro on 15/5/11.*/varPfuns =function () {     This. Flag = 0;}//Perform an effectPFUNS.RUNEFFATTACK_SP =function(SP, URL, name, num, speed, loop, delay, zorder, scale, tag, CP) {varSprite =sp; varSp_eff =Newcc.    Sprite (); varAnimation =Newcc.    Animation ();  for(vari = 1; I <= num; i++) {        varToi= ""; if(i<10) {toi= "0" +i; }        Else{toi=i; }        varFrameName = Url + "/" + name + Toi + ". png"; MLOG.C ("Framename>>" +framename); varframe =Gameframecache.getcache (framename); if(frame!=NULL) {mlog.c ("Framename>ok>>" +framename);        Animation.addspriteframe (frame); }    }    varUsetime = 1/parseint (speed);    Animation.setdelayperunit (Usetime); Animation.setrestoreoriginalframe (true);    Animation.setloops (loop); varAction =cc.animate (animation); varActdelay2 =cc.    Delaytime.create (delay); if(delay>0) {sp_eff.runaction (cc.    Sequence (Actdelay2,action,cc.callfunc (Pfuns.effremove, Sp_eff)); }    Else{sp_eff.runaction (cc).    Sequence (Action,cc.callfunc (Pfuns.effremove, Sp_eff)); }    if(cp!=NULL) {sp_eff.setposition (CC.P (CP.X,CP.Y)); }    Else{sp_eff.setposition (CC.P (Sprite.getcontentsize (). Width/2,sprite.getcontentsize (). HEIGHT/2));    } sp_eff.setscale (scale); Sprite.addchild (Sp_eff,zorder,tag);};//removed fromPfuns.effremove =function () {     This. Removefromparent ();};
View Code

We use frame animation to play the skill effects, frame animation frames for each frame to get the way to use:

var frame =gameframecache.getcache (framename);

OK, we can run up and look at the effect:

Our skill frame animations have been beautifully rendered out! It looks really good! Then this little knowledge point will be finished!

OK, so let's take a look at the asynchronous loading of all our images! We know that Texturecache is available in the COCOS2DX.

Help us to achieve image resource file management, and use.

Imagine whether we need to use the image temporarily loading the picture quickly, or first through a loading interface to load the resources, in from Texturecache

Get it out.

The answer is of course the latter!

So now we're going to do the implementation of loading asynchronous loading, the Gameframecache.js class has

Gameframecache. Setallcache

Such a method, by traversing all the PNG files in our Res directory to get the file path, and load all the pictures;

Note here: Res This array can only fill in png,jpg and other picture file types

It is possible to write our various file paths in this way.

Next we'll implement a progress bar implementation to asynchronously load all of our program resources and add two methods to Mainlayer:

    //Load Progress barInitloadingbar:function(sp_loading) {//Load Loading Bar        varSp_loadingtiao =Newcc. Sprite (Res.        Uiloadingbd_png); Sp_loadingtiao.attr ({x:sp_loading.getcontentsize (). Width/2, Y:sp_loading.getcontentsize (). height/2-180, Scale:1, Rotation:0        }); Sp_loading.addchild (Sp_loadingtiao,1); varLoadingbar =NewCcui. Loadingbar (Res.        Uiloadingbar_png); Loadingbar.x= Sp_loading.getcontentsize (). Width/2;        Loadingbar.y = Sp_loading.getcontentsize (). height/2-180; Sp_loading.addchild (loadingbar,2, Loadingbar_tag); Loadingbar.setpercent (0); },
//Resource Loadding Buffer Progress callbackSetloadingbar:function(){ varPernum = parseint (Loadingbarpronum/loadingbarproallnum *100); MLOG.C ("Pernum >>" +pernum); Loadingbarpronum++; varLoadingbar = This. Getchildbytag (Loadingbar_tag); if(loadingbar!=NULL) {loadingbar.setpercent (pernum); } //the progress bar is loaded to jump if(pernum==100) { //Load CompleteMLOG.C ("Asynchronous Load Resource Complete"); PFUNS.RUNEFFATTACK_SP ( This, "Skill_dianjin", "000", 13, 6, 3, 1, 11111, 1, 1000,NULL); } },

Setloadingbar This method is our callback, and the Gameframecache will use the Addimageasync method for the successful callback of the resource load!

And get two values:

var Loadingbarpronum = 1; var loadingbarproallnum=0;

and Loadingbarproallnum to carry out the calculation and update of the progress bar;

When the ratio of the last progress bar is 100, then play our skill animations:

Texcache.addimageasync (Reslist[key], objcallback, obj);

At the end of the constructor, add the calling method directly:

        // Load progress bar call        this. Initloadingbar (this);         // asynchronously loads all resource calls        Gameframecache.setallcache (This,this. setloadingbar);        

This enables the asynchronous loading of picture resources for our entire project.

We can run up and look at the effect!

Well, the knowledge points in this chapter are very common in our game development and are very important! So I think it will be helpful to everyone!

Knowledge points in this section source code:

SOURCE Download (Baidu disk)

Create a new project yourself, unzip the downloaded file, copy all the files to your new project directory and all the overlays can run!

"Basic Teaching of COCOS2D-JS (5) Use of resource packaging tools and asynchronous loading processing of resources"

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.