關(guān)于預(yù)制體的介紹官網(wǎng)有相關(guān)闡述:
http://docs.cocos.com/creator/manual/zh/asset-workflow/prefab.html
關(guān)于對(duì)象池的官網(wǎng)相關(guān)闡述:
http://docs.cocos.com/creator/manual/zh/scripting/pooling.html
下面我們開始制作預(yù)制體.
- 將資源管理器的圖片 拖到 層級(jí)管理器, 生成了pipe
然后創(chuàng)建一個(gè)空節(jié)點(diǎn)命名成pipe_prefab作為父節(jié)點(diǎn), 將pipe拖到pipe_prefab中作為子節(jié)點(diǎn), 然后再復(fù)制一個(gè).
現(xiàn)在倆個(gè)子節(jié)點(diǎn)疊加在一起,將倆個(gè)子節(jié)點(diǎn)的錨點(diǎn)Anchor的Y值設(shè)為0, 再將bottom節(jié)點(diǎn)的Scale的Y值設(shè)為-1. 效果如下
這時(shí)將pipe_prefab拖到res/prefab目錄下, 這時(shí)prefab已初步做好, 可以將層級(jí)管理器的pipe_prefab刪掉了
雙擊res/prefab/pipe_prefab, 再分別選中top節(jié)點(diǎn)和bottom節(jié)點(diǎn), 給top和bottom節(jié)點(diǎn)添加boxCollider,使它具有碰撞屬性
然后選中pipe_prefab,添加boxCollider,并設(shè)置size 和offset, 這個(gè)碰撞是用于后續(xù)統(tǒng)計(jì)分?jǐn)?shù)的.
我們給pipe添加一個(gè)腳本,用來控制管道.
cc.Class({
extends: cc.Component,
start () {
this.bottom = this.node.getChildByName("bottom");
this.bottom.y = -300*Math.random();
this.top = this.node.getChildByName("top");
this.top.y = this.bottom.y + 200 + Math.random()*400;
},
update (dt) {
this.node.x -= 100*dt;
if(this.node.getBoundingBoxToWorld().xMax < 0) {
D.pipeManager.recyclePipe(this.node);
}
},
});
D是全局變量, 定義在Global.js文件中
window.Global = {
State : cc.Enum({
Run : 0,
Over: 1
})
};
window.D = {
gameController : null,
pipeManager : null,
};
再添加一個(gè)管道m(xù)anager, 用來管理pipe,每當(dāng)pipe的x坐標(biāo)小于0px,就回收它
const Pipe = require('Pipe');
cc.Class({
extends: cc.Component,
properties: {
pipePrefab: cc.Prefab,
addInterval : 0
},
onLoad () {
D.pipeManager = this;
this.pipePool = new cc.NodePool();
},
start () {
this.addPipe(0,600);
this.addPipe(0,1000);
this.addPipe(0,1400);
this.schedule(this.addPipe, this.addInterval);
},
addPipe (time,x) {
if(x == null)
x = 1400;
let pipe = this.pipePool.get();
if(pipe == null) {
pipe = cc.instantiate(this.pipePrefab);
}
pipe.active = true;
pipe.x = x;
this.node.addChild(pipe);
},
recyclePipe(pipe) {
pipe.active = false;
this.pipePool.put(pipe);
}
});