cocos2djs 如今已經火到爆,大家可以根據極客學院的教程走一遍 體驗下js開發游戲的魅力.
這是一個很簡單的游戲, 不同顏色的小鳥會隨機出現在屏幕上, 在規定時間內盡可能打死最多的小鳥. 分數和 時間分別顯示在屏幕 左上角 和右上角.
場景部分
我們需要3個場景
- 開始場景
- 游戲場景
- 結束場景
開始場景很簡單 一個背景 加上一個開始按鈕
游戲場景 是我們核心部分 我們會在這里創建小鳥 然后飛行 通過觸摸交互去殺死它們
結束場景 很簡單就不貼圖了
核心部分
最核心的算法部分 應該是小鳥隨機從屏幕中飛過了,這里采用簡單的隨機數.來模擬
鳥飛行的方向
1 : 鳥從右邊進入 飛向左邊
-1 : 左邊進入飛向 右邊
<pre>
<code>
var way = Math.random() > 0.5 ? 1: -1;
</code>
</pre>
Math.random() 會生成0.0 - 1.0 之間的隨機數字 也就是 0.0 < x < 1.0 不包括 0 和 1.采用0.5作為左右分界線.
鳥飛行的時間
我們假設 小鳥需要 1 - 3 秒 飛行到屏幕外邊.
<pre>
<code>
var time = Math.floor(1+Math.random()*3);
</code>
</pre>
注意下 Math.floor 用來取整數 加上 Math.random()*3 取得 [0,1,2] 3個整數. 在+1 取得[1,2,3]
鳥的坐標
<pre>
<code>
var size = cc.winSize;
var startPos = cc.p(way == 1 ?size.width:0, Math.random() * size.height);
var endPos = cc.p(way == 1 ? 0 : size.width, Math.random() * size.height);
</code>
</pre>
startPos 小鳥進入屏幕的坐標 這個地方通過前面方向(way)的判斷來 確定小鳥從左邊還是右邊進入. 如果是右邊的話,那么就是 屏幕右邊 貼著屏幕邊 的任意隨機高度進入屏幕 飛向左邊。
endPos 相反而已.
模擬小鳥飛翔
借助cocos2d action 來模擬飛行.
<pre>
<code>
var bird = new cc.Sprite(res.bird_png,this._birdRect[Math.floor(Math.random() * 4)]);
//縮放下
bird.setScale(-0.5*way,0.5);
bird.setAnchorPoint(cc.p(0,0.5));
bird.setPosition(startPos);
this._birdLayer.addChild(bird);
this._birdList.push(bird);
var _this = this;
//小鳥動起來
bird.runAction(new cc.Sequence(
new cc.MoveTo(time,endPos),
//結束執行
new cc.CallFunc(function(){
for(var i=0; i <_this._birdList.length;i++){
var b = _this._birdList[i];
//刪除掉當前的小鳥
if(b == bird){
//指定位置刪除 刪除數量
_this._birdList.splice(i,1);
//從layer中移除
bird.removeFromParent();
break;
}
}
})
));
</code>
</pre>
runAction會執行動作函數 然后一個序列 來執行。 moveTo 指定了飛行結束位置 endPos 然后callFuns 為 動畫執行完成的回調 這里我們刪除了小鳥 在數組中的位置 以及從 父層中刪掉.因為它飛到屏幕外面了 不需要了.
####### 觸摸打鳥
我們需要在 onEnter中添加 單點觸摸事件.
<pre>
<code>
onEnter : function(){
this._super();
this._step = 0;
//啟動update函數
this.scheduleUpdate();
//添加鼠標事件
var _this = this;
this._touchEvent = new cc.EventListener.create({
//單點觸摸
event : cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches : true,
onTouchBegan: function(touch,event){
//新創建的小鳥在數組后面 屏幕上面 所以我們這里要逆向遍歷
for(var i = _this._birdList.length -1; i >=0 ; i--){
var bird = _this._birdList[i];
//獲得小鳥的碰撞包圍盒
var box =bird.getBoundingBox();
//檢測碰撞是否生效 box 和 當前點擊的位置
if(cc.rectContainsRect(box,touch.getLocation())){
//當前分數+1
_this._scoreValue += 1;
_this._countdownSprite.setString(_this._scoreValue);
//移除bird bird死亡
_this._birdList.splice(i,1);
bird.removeFromParent();
break;
}
}
//如果為true 繼續檢測后面事件 進行事件傳播
return false;
}
});
//加入到事件管理器中
cc.eventManager.addListener(this._touchEvent,this);
},
//退出
onExit : function(){
this._super();
//關閉update函數
this.unscheduleUpdate();
//移除事件
cc.eventManager.removeListener(this._touchEvent);
},
</code>
</pre>
別忘了退出場景的時候 清除掉 事件.