Cocos2dx-JS学习01

1
2
3
4
5
6
<body>
<script src="res/loading.js"></script>
<canvas id="gameCanvas" width="480" height="720"></canvas>
<script src="frameworks/cocos2d-html5/CCBoot.js"></script>
<script cocos src="main.js"></script>
</body>

首先加载的是CCBoot.js文件

CCBoot.js

执行主循环

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Run main loop of director
*/
mainLoop: function () {
if (this._purgeDirectorInNextLoop) {
this._purgeDirectorInNextLoop = false;
this.purgeDirector();
}
else if (!this.invalid) {
this.drawScene();
}
},

_purgeDirectorInNextLoop:下一帧是否需要清除自身,一般在cc.director.end()赋值为true

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
/**
* Draw the scene. This method is called every frame. Don't call it manually.
*/
drawScene: function () {
var renderer = cc.renderer;

// calculate "global" dt
this.calculateDeltaTime();

//tick before glClear: issue #533
if (!this._paused) {
this._scheduler.update(this._deltaTime);
cc.eventManager.dispatchEvent(this._eventAfterUpdate);
}


//首先执行调度器中的任务,然后触发cc.director.EVENT_AFTER_UPDATE事件,检查交互事件,有的话就分发处理




/* to avoid flickr, nextScene MUST be here: after tick and before draw.
XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */
if (this._nextScene) {
this.setNextScene();
}
//如果有场景切换,便切换

//渲染当前scene
// draw the scene
if (this._runningScene) {
if (renderer.childrenOrderDirty) {
cc.renderer.clearRenderCommands();
cc.renderer.assignedZ = 0;
this._runningScene._renderCmd._curLevel = 0; //level start from 0;
this._runningScene.visit();
renderer.resetFlag();
}
else if (renderer.transformDirty()) {
renderer.transform();
}
}

renderer.clear();

// draw the notifications node
if (this._notificationNode)
this._notificationNode.visit();
//遍历节点,更新节点的空间转换矩阵,发送指令给渲染器
cc.eventManager.dispatchEvent(this._eventAfterVisit);
cc.g_NumberOfDraws = 0;

renderer.rendering(cc._renderContext);
this._totalFrames++;
//排序,绘制
cc.eventManager.dispatchEvent(this._eventAfterDraw);
cc.eventManager.frameUpdateListeners();
//更新帧率
this._calculateMPF();
},

关于绘制管理

关于内存管理(引用计数法)

调度器

cc.Node有相关API

1
2
3
4
node.scheduleUpdate()
node.update = function (dt) {

}

默认调度器:使用scheduleUpdate,必须重写update函数,dt是时间间隔

自定义调度器:

1
node.schedule(callback,inteval,repeate,delay,key)

回调函数(必须),时间间隔(默认0),重复次数(默认cc.REPEAT_FOREVER),延时时间(默认0),唯一标示符

卸载调度器:

unschedule和unscheduleAllCallbacks

场景管理

使用栈的结构

在退出的相关生命周期函数中,应该将this._super()函数放在最后调用,遵循“先进后出“

A->B

SceneA的onEixtTransitionDidStart方法开始前SceneB的ctor执行,所以不要在ctor中做开销大的工作

精灵

每个精灵一般关联一张纹理(Texture2D对象)

四种方法创建