您的位置:首页 > 移动开发 > Cocos引擎

从零开始,使用Cocos2d HTML5完成一个游戏——第一步

2013-09-06 16:37 591 查看
从零开始,使用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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐