Appearance
打字机效果类
主要为了实现逐字显示的效果
使用方法
- 将
TypeWriter脚本挂载到含有cc.Label组件的节点上 - 在编辑器 Inspector 中将 Label 组件拖入
label属性槽(或留空,脚本会在onLoad时自动获取) - 在其他脚本中调用
setData(text, speed?)启动打字效果:
ts
// 获取组件
const typeWriter = this.node.getComponent(TypeWriter);
// 以默认速度(每0.1秒一个字)开始打字
typeWriter.setData("你好,世界!");
// 自定义打字间隔(单位:秒)
typeWriter.interval = 0.05; // 更快的速度
typeWriter.setData("欢迎来到游戏!");
// 立即显示全部文字(跳过打字动画)
typeWriter.writeOver();
// 判断是否正在打字中
if (typeWriter.isWriting) {
cc.log("正在打字...");
}ts
const { ccclass, property } = cc._decorator;
/**
* 打字机效果类
*/
@ccclass
export default class TypeWriter extends cc.Component {
/** 显示文本的Label组件 */
@property(cc.Label) label: cc.Label = null;
/** 状态: 0-待机, 1-打字中, 2-完成 */
state: number = 0;
/** 当前拼接id */
id: number = 0;
/** 输入文本拆分后的数组 */
arr: Array<string> = [];
/** 频率,不能超过每帧的间隔时间 */
interval: number = 0.1;
curStr = '';
/** 是否正在打字 */
get isWriting() {
return (this.state == 1) ? true : false;
}
onLoad() {
if (!this.label) this.label = this.node.getComponent(cc.Label);
}
onEnable() {}
onDisable() {
this.reset();
}
reset() {
this.unschedule(this.write);
this.id = 0;
this.state = 0;
this.curStr = '';
this.arr = [];
this.render();
}
setData(txt) {
this.reset();
this.state = 1;
this.arr = txt.split('');
this.schedule(this.write, this.interval, cc.macro.REPEAT_FOREVER, 0);
}
write() {
if (this.id >= this.arr.length) {
this.unschedule(this.write);
this.state = 2;
return;
}
this.curStr += this.arr[this.id];
this.id++
this.render()
}
writeOver() {
this.unschedule(this.write);
this.state = 2;
this.id = this.arr.length;
this.curStr = this.arr.join('');
this.render();
}
render() {
this.label.string = this.curStr;
}
}