突然想搞个打字机特效玩玩看,就是让Label的内容一个字一个字的显示出来,很多游戏的对话框内容就是这样显示的。
实现这个特效的常规方案就是使用setTimeout或者setInterval,亦或者cc里边的schedule。
代码比较简单,但是我的本意是想封装成可复用的,还尝试过修改cclabel,结果没成功。


cc.Class({
extends: cc.Component,
properties: {
label: {
default: null,
type: cc.Label,
},
isCompleted: true,
},
onLoad: function () {
this.textInterval("点击屏幕动态显示");
this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
if(this.isCompleted) {
this.isCompleted = false;
this.textInterval("床前明月光,\n疑是地上霜。\n举头望明月,\n低头思故乡。");
}
}, this);
},
textInterval: function(text) {
let self = this;
let index = 0;
text = text || "";
let func = setInterval(function () {
if(index < text.length) {
self.label.string = text.substr(0, ++index);
return;
}
clearInterval(func);
self.isCompleted = true;
}, 100);
},
});