從零開始,使用Cocos2d HTML5完成一個遊戲——第二步:滑鼠互動
歡迎來到Cocos2d HTML5制作完整遊戲第二課。這次我們準備給遊戲添加滑鼠互動。基于原來的遊戲上,現在你要用滑鼠移動一個紅色圓圈。當你點選滑鼠的時候你會拆毀一個圓圈,并且分發4發子彈上下左右飛出去。下面是我們今天要做的時候的步驟。從第一步開始,你隻要改變circlechain.js檔案:
var circlechain = cc.Scene.extend({
onEnter:function(){
this._super();
var layer = new circleChainGame();
layer.init();
this.addChild(layer);
}
})
var gameLayer;
var bulletSpeed=5;
var circleChainGame = cc.Layer.extend({
init:function(){
this._super();
this.setMouseEnabled(true);
var circleSpeed = 2;
var s = cc.Director.getInstance().getWinSize();
gameLayer = cc.LayerColor.create(new cc.Color4B(0, 0, 0, 255), 500, 500)
for(i=0;i<10;i++){
var greenCircle = cc.Sprite.create("greencircle.png");
var randomDir = Math.random()*2*Math.PI;
greenCircle.xSpeed=circleSpeed*Math.cos(randomDir);
greenCircle.ySpeed=circleSpeed*Math.sin(randomDir);
gameLayer.addChild(greenCircle);
greenCircle.setPosition(new cc.Point(Math.random()*500,Math.random()*500));
greenCircle.schedule(function(){
this.setPosition(new cc.Point(this.getPosition().x+this.xSpeed,this.getPosition().y+this.ySpeed));
if(this.getPosition().x>500){
this.setPosition(new cc.Point(this.getPosition().x-500,this.getPosition().y));
}
if(this.getPosition().x<0){
this.setPosition(new cc.Point(this.getPosition().x+500,this.getPosition().y));
}
if(this.getPosition().y>500){
this.setPosition(new cc.Point(this.getPosition().x ,this.getPosition().y-500));
}
if(this.getPosition().y<0){
this.setPosition(new cc.Point(this.getPosition().x ,this.getPosition().y+500));
}
})
}
redCircle=cc.Sprite.create("redcircle.png");
gameLayer.addChild(redCircle);
this.addChild(gameLayer);
return true;
},
onMouseDown:function (event) {
var location = event.getLocation();
gameLayer.removeChild(redCircle);
for(i=0;i<4;i++){
var redBullet = cc.Sprite.create("redbullet.png");
redBullet.xSpeed=bulletSpeed*Math.cos(i*Math.PI/2);
redBullet.ySpeed=bulletSpeed*Math.sin(i*Math.PI/2);
gameLayer.addChild(redBullet);
redBullet.setPosition(location);
redBullet.schedule(function(){
this.setPosition(new cc.Point(this.getPosition().x+this.xSpeed,this.getPosition().y+this.ySpeed));
if(this.getPosition().x>500 || this.getPosition().y>500 || this.getPosition().x<0 || this.getPosition().y<0){
gameLayer.removeChild(this);
}
})
}
},
onMouseMoved:function(event){
var location = event.getLocation();
redCircle.setPosition(location);
}
})
之後你會看到:
【效果請在原網頁檢視】
用滑鼠移動紅色圓圈,并且點選舞台讓圓圈炸開。下次我會告訴你完整的連鎖反應,并且下次會完整的注釋代碼
原文連結:http://www.emanueleferonato.com/2013/05/21/from-zero-to-a-complete-game-with-cocos2d-html5-step-2-mouse-interaction/