CocosCreator碰撞系統(tǒng)
Cocos Creator 是一個完整的游戲開發(fā)解決方案,包含了 cocos2d-x 引擎的 JavaScript 實現(xiàn),以及快速開發(fā)游戲所需求的各種圖形界面東西。Cocos Creator 的編輯器完全為引擎定制打造,包含從規(guī)劃、開發(fā)、預覽、調試到發(fā)布的整個工作流所需的全功能,該編輯器供給面向規(guī)劃和開發(fā)的兩種工作流,供給簡略順暢的分工合作方法。Cocos Creator 現(xiàn)在支持發(fā)布游戲到 Web、Android 和 iOS,真正實現(xiàn)一次開發(fā),全渠道工作。Cocos Creator 是以內容創(chuàng)作為中心的游戲開發(fā)東西,在 Cocos2d-x 基礎上實現(xiàn)了完全腳本化、組件化和數(shù)據(jù)驅動等特征。
碰撞組件
首先來看碰撞組件。CocosCreator提供了三種碰撞組件:Box Collider,Circle Collider,Polygon Collider。增添十分簡單,只需要選中節(jié)點在屬性檢查器中選擇添加組件。

這里使用的是Box Collider,可以看到節(jié)點周圍多了一個綠色的框,這就是碰撞體。

在屬性檢查器中可以看到碰撞體的屬性,選中Editing可以通過拖動對其大小進行修改。

另外兩種碰撞組件和Box Collider就是形狀區(qū)別。
碰撞腳本控制
下面來看碰撞的腳本。首先需要開啟碰撞檢測系統(tǒng)和debug繪制接口,默認情況下是禁用的。碰撞檢測系統(tǒng)功能不需要多說,debug繪制是用于顯示碰撞組件的碰撞檢測范圍的。
cc.director.getCollisionManager().enabled = true;
cc.director.getCollisionManager().enabledDebugDraw = true;
如果希望顯示碰撞組件的包圍盒,可以開啟另一個接口,我沒有發(fā)現(xiàn)這個接口的用處。
cc.director.enabledDrawBoundingBox = true;
接下來看下碰撞系統(tǒng)的回調函數(shù),主要有三個:
碰撞產(chǎn)生時調用onCollisionEnter: function (other, self)
碰撞保持時調用onCollisionStay: function (other, self)
碰撞結束時調用onCollisionExit: function (other, self)
other是產(chǎn)生碰撞的另一個碰撞組件,self是產(chǎn)生碰撞的自身的碰撞組件。
示例的具體代碼如下:
cc.Class({
extends: cc.Component,
properties: {
// foo: {
// default: null,
// url: cc.Texture2D, // optional, default is typeof default
// serializable: true, // optional, default is true
// visible: true, // optional, default is true
// displayName: 'Foo', // optional
// readonly: false, // optional, default is false
// },
// ...
},
// use this for initialization
onLoad: function () {
cc.director.getCollisionManager().enabled = true;
cc.director.getCollisionManager().enabledDebugDraw = true;
cc.director.getCollisionManager().enabledDrawBoundingBox = true;
this.touchingNumber = 0;
},
onCollisionEnter: function (other) {
this.node.color = cc.Color.RED;
this.touchingNumber ++;
cc.log(this.touchingNumber);
},
onCollisionStay: function (other) {
// console.log('on collision stay');
},
onCollisionExit: function () {
this.touchingNumber --;
cc.log(this.touchingNumber);
if (this.touchingNumber === 0) {
this.node.color = cc.Color.WHITE;
}
}
// called every frame, uncomment this function to activate update callback
// update: function (dt) {
// },
效果如圖:
碰撞前

碰撞時
