cocos creator制作一个小游戏【FlappyBird】

首先我们建一个空项目,进去后建立一个文件夹scenes,用来存放场景, 然后右键选择创建一个scene

接下来, 创建一个res目录,把我们需要的资源丢进去.

然后双击scenes文件夹下的game场景, 来编辑它, 进入场景后创建一个空节点sky,用来展示天空

然后在sky节点下创建一个子节点sky1,再将锚点Anchor设置为(0,0),然后设置位置Position(0,400),

然后选中sky1, 将bg拖到右侧的Sprite Frame中, 再将锚点Anchor设置为(0,0),

再复制一个节点命名为sky2, 设置位置Position(900,0),如下图:

创建scrips文件夹用来存放脚本,创建Scroller来控制sky.并将Scroller脚本添加到sky节点组件中,如下图:

Scroller脚本代码如下, speed是每秒走的距离, resetX是重置的位置

cc.Class({

extends: cc.Component,

properties: {

//-- 滚动的速度

speed:0,

//-- X轴边缘

resetX:0

},

update:function(dt){// dt约为0.01667, 1秒钟60dt.

if(D.gameController.state != Global.State.Run)

return;

letx =this.node.x;

this.node.x +=this.speed*dt;

if(x <=this.resetX) {

this.node.x -=this.resetX;

}

}

});

这俩个值可以在cocos creator编辑.

按照创建sky的方式来创建ground

然后我们创建不动的背景块

设置颜色, 锚点, 位置

然后以同样的方式创建蓝色的背景块

到这里背景就创建完成了.

下面我们开始制作预制体.

将资源管理器的图片  拖到  层级管理器, 生成了pipe

然后创建一个空节点命名成pipe_prefab作为父节点, 将pipe拖到pipe_prefab中作为子节点, 然后再复制一个.

现在俩个子节点叠加在一起,将俩个子节点的锚点Anchor的Y值设为0,  再将bottom节点的Scale的Y值设为-1. 效果如下

这时将pipe_prefab拖到res/prefab目录下, 这时prefab已初步做好, 可以将层级管理器的pipe_prefab删掉了

双击res/prefab/pipe_prefab, 再分别选中top节点和bottom节点, 给top和bottom节点添加boxCollider,使它具有碰撞属性

然后选中pipe_prefab,添加boxCollider,并设置size 和offset,  这个碰撞是用于后续统计分数的.

我们给pipe添加一个脚本,用来控制管道.

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,

};

再添加一个管道manager, 用来管理pipe,每当pipe的x坐标小于0px,就回收它

constPipe =require('Pipe');

cc.Class({

extends: cc.Component,

properties: {

pipePrefab: cc.Prefab,

addInterval:0

},

onLoad () {

D.pipeManager =this;

this.pipePool =newcc.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;

letpipe =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);

}

});

到目前为止管道已经生成好了

视频教程可以关注领取得到哦点击链接加入群聊【cocos/unity交流群】

作者:Black_Blue

来源:

声明:发布此文是出于传递更多知识以供交流学习之目的。若有来源标注错误或侵犯了您的合法权益,请作者持权属证明与我们联系,我们将及时更正、删除,谢谢

你可能感兴趣的:(cocos creator制作一个小游戏【FlappyBird】)