Cocos2d-js层的生命周期函数

来源:互联网 发布:如何申请淘宝店铺 编辑:程序博客网 时间:2024/06/14 12:15

许多刚学习Cocos2d-js的小伙伴,总是会在教程书籍的代码上看到 ctor:function()、onEnter:function()这些的函数,而且基本每一个程序上都用了这些程序,然后有一些小伙伴,并不知道这些函数的意义,这里笔者来列举一下。

层(Layer)的生命周期函数
ctor:构造函数,在初始化这个层的时候会调用这个函数
onEnter:在进入这个层的时候会调用
onEnterTransitionDidFinish:在进入这个层并在切换的过渡动画结束时会调用这个函数
onExit:在退出这个层的时候会调用
onExitTransitionDidStart:在退出这个层并在切换的过渡动画开始时会调用这个函数

下面举一个场景切换的例子来说明这些函数调用的顺序。
定义A、B两个场景,这两个场景分别有一个ALayer层和BLayer层。ALayer层和BLayer层部分代码如下:

//A场景中ALayer层var ALayer = cc.Layer.extend({    sprite:null,    ctor:function () {        this._super();        cc.log("A-ctor");        /*var size = cc.director.getWinSize();        cc.MenuItemFont.setFontName("Times New Roman");        cc.MenuItemFont.setFontSize(86);        var item = new cc.MenuItemFont("pushScene",this.menuItemCallback,this);        var mn = new cc.Menu(item);        mn.alignItemsVertically();        this.addChild(mn);*/        return true;    },    menuItemCallback:function (sender) {        cc.director.pushScene(new BScene);    },    onEnter:function () {        this._super();        cc.log("A-onEnter");    },    onEnterTransitionDidFinish:function () {        this._super();        cc.log("A-onEnterTransitionDidFinish");    },    onExit:function () {        this._super();        cc.log("A-onExit");    },    onExitTransitionDidStart:function () {        this._super();        cc.log("A-onExitTransitionDidStart");    }});----------//B场景中BLayer层var BLayer = cc.Layer.extend({    sprite:null,    ctor:function () {        this._super();        cc.log("B-ctor");        /*cc.MenuItemFont.setFontName("Times New Roman");        cc.MenuItemFont.setFontSize(86);        var item = new cc.MenuItemFont("popScene",this.menuItemCallback,this);        var mn = new cc.Menu(item);        mn.alignItemsVertically();        this.addChild(mn);*/        return true;    },    menuItemCallback:function (sender) {        cc.director.popScene();    },    onEnter:function () {        this._super();        cc.log("B-onEnter");    },    onEnterTransitionDidFinish:function () {        this._super();        cc.log("B-onEnterTransitionDidFinish");    },    onExit:function () {        this._super();        cc.log("B-onExit");    },    onExitTransitionDidStart:function () {        this._super();        cc.log("B-onExitTransitionDidStart");    }});

现在假设两种场景切换的情况:
(1)使用pushScene函数,从A场景进入B场景
(2)使用popScene函数,从B场景返回A场景

当情况(1)时,层的生命周期函数调用顺序如下图(程序运行先加载了A场景):
这里写图片描述

当情况(2)时,层的生命周期函数调用顺序如下图(在B场景点击popScene):
这里写图片描述