在Main场景中,将Game和Canvas分开,一个主要用于处理逻辑,一个主要用于处理UI相关。
注意:Canvas要放在下面,不能被遮挡。
编写脚本GameUI用于控制UI相关的节点,挂到Canvas上。
cc.Class({
extends: cc.Component,
properties: {
//公布UI组件
lbTime:cc.Label,
lbScore:cc.Label,
progressBar:cc.ProgressBar
},
start () {
//js的对象存取器 (对象, 属性名{get接口,set接口()})
//}
let temp = 0; //初始分数
Object.defineProperty(cc,'score',{
//当对象的属性被访问就会调用这个接口
get(){
return temp;
},
//当这个对象的对应属性被修改就会调用set接口
set:(value)=>{
temp = value;
this.lbScore.string = '分数:'+value;
}
});
if(cc.pageIndex === 0){
//标签组件.node:标签节点。
this.lbTime.node.active = false;
this.progressBar.node.active = false;
}
else{
this.progressBar.node.active = true;
this.lbTime.node.active = true;
//定义一个变量插到this里面,即在当前脚本的任何地方都能够访问。
this.time = 10.0;
let totalTime = this.time;
//标签显示的内容
this.lbTime.string ='时间:'+this.time.toFixed(2)+'秒';
let cutTime = (dt)=>{
//倒计时,如果游戏没有开始,不倒计时
if(!cc.isGameStart){
return;
}
this.time-=dt;
//计算剩余时间百分比
let progress = this.time/totalTime;
//只需要设置进度条组件的progress属性
this.progressBar.progress = progress;
this.lbTime.string ='时间:'+this.time.toFixed(2)+'秒';
if(this.time<=0){
cc.isGameStart = false;
this.lbTime.string ='时间:0.00秒';
//关闭定时器
this.unschedule(cutTime);
}
}
//倒计时,开定时器
this.schedule(cutTime,0.01);
}
},
});