官方文档:http://docs.cocos/creator/manual/zh/scripting/scheduler.html
需求:
做一个自动恢复精力的功能,每秒恢复一点,直到精力达到最大值则停止恢复;
代码:
onLoad () {
//获取常驻节点
var node = cc.director.getScene().getChildByName("dataNode");
this.userInfo = node.getData().userInfo;
// 是否正在恢复
this.isRecorver = false;
},
// 精力恢复
energyRecorver(){
let _this = this;
if(_this.isRecorver || _this.userInfo.max_energy == _this.userInfo.energy) return;
_this.isRecorver = true;
_this.callback = function(){
if(_this.userInfo.max_energy == _this.userInfo.energy){
_this.unschedule( _this.callback)
_this.isRecorver = false;
return;
}
_this.userInfo.energy += _this.userInfo.recover_speed;
}
_this.schedule(_this.callback,1)
},
update (dt) {
this.energyRecorver()
}
逻辑:
每次更新都会调用 energyRecorver(),所以加了个参数 isRecorver是否正在恢复,如果是正在恢复,或者已经恢复满了,则不再往下执行。
执行精力恢复的时候,如果精力值满了,则关闭当前计时器,且调整参数 isRecorver的值为false;
页面效果:
这是userInfo里面的初始数据,初始精力先设成50,最大精力为100:
将energy的值打印出来,效果如下:
它会每秒加一,然后到100时停下。
更多推荐
cocosCreator 计时器 schedule
发布评论