找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/core/utility/UtilityString.ts
1import { _decorator, Label, Node, tween } from 'cc';
2
3export class UtilityString {
4 /** 安全读取非空字符串,避免把 undefined/null 转成字面量字符串。 */
5 public static ReadNonEmptyString(value: unknown): string {
6 return typeof value === "string" ? value.trim() : "";
7 }
8
9 /**
10 * 格式化字符串
11 * @param str 字符串
12 * @param args 参数
13 * @returns 格式化后的字符串
14 */
15 public static Format(str: string, ...args: any): string {
16 return str.replace(/{(\d+)}/g, (match, index) => {
17 return typeof args[index] !== 'undefined' ? args[index] : match;
18 });
19 }
20
21
22 /**
23 * 打字机效果
24 * @param label 文本组件
25 * @param text 完整文本
26 * @param speed 打字速度(字符/秒)
27 * @param onComplete 完成回调
28 * @param onCharTyped 每个字符输入时的回调
29 * @returns 打字机动画实例,可用于中途停止
30 */
31 public static TypewriterEffect(label: Label, text: string, speed: number = 2, onComplete?: () => void, onCharTyped?: () => void) {
32 // 清除之前的文字
33 label.string = '';
34
35 // 计算每个字符的间隔时间
36 const interval = 1 / speed;
37
38 // 创建打字机效果
39 let currentIndex = 0;
40
41 // 使用tween创建打字机动画
42 const typewriterTween = tween({ index: 0 })
43 .repeat(text.length,
44 tween()
45 .to(interval, { index: currentIndex + 1 })
46 .call(() => {
47 currentIndex++;
48 label.string = text.substring(0, currentIndex);
49 // 每个字符输入后调用回调
50 onCharTyped?.();
51 })
52 )
53 .call(() => {
54 onComplete?.();
55 })
56 .start();
57
58 return typewriterTween;
59 }
60
61
62 /**
63 * 停止打字机效果
64 * @param tween 打字机动画实例
65 */
66 public static StopTypewriterEffect(tween: any) {
67 if (tween) {
68 tween.stop();
69 }
70 }
71
72
73 /**
74 * 时间单位转换
75 * @param time 时间格式-时间戳-时间(ms-千分位) 转换格式
76 * @param format 格式化字符串(例:yyyy-MM-dd hh:mm:ss)
77 */
78 public static dateToFormate(time: number | Date | string, format: string = '') {
79 let dateTime: Date;
80 switch (typeof time) {
81 case "string":
82 dateTime = new Date(time);
83 break;
84 case "number":
85 dateTime = new Date(time);
86 break;
87 default:
88 dateTime = time;
89 break;
90 }
91 let o: any = {
92 "y+": dateTime.getFullYear(), // year
93 "M+": dateTime.getMonth() + 1, // month
94 "d+": dateTime.getDate(), // day
95 "h+": dateTime.getHours(), // hour
96 "m+": dateTime.getMinutes(), // minute
97 "s+": dateTime.getSeconds(), // second
98 "q+": Math.floor((dateTime.getMonth() + 3) / 3), // quarter
99 "S": dateTime.getMilliseconds() // millisecond
100 }
101
102 for (let k in o) {
103 const reg = new RegExp("(" + k + ")");
104 if (reg.test(format)) {
105 const count = format.match(reg)![0].length;
106 let str = ''
107 for (let i = 0; i < count; i++) {
108 str += '0'
109 }
110 format = format.replace(reg, (str + o[k]).substring(("" + o[k]).length));
111 }
112 }
113 return format;
114 }
115 /**
116 * 时间秒数转换为格式化字符串
117 * @param time 当前秒数
118 * @param format 格式化字符串(例:yyyy-MM-dd hh:mm:ss)
119 */
120 public static dateToFormateBySecond(time: number, format: string = '') {
121 const o: any = {
122 "y+": Math.floor(time / 86400 / 365).toString(),
123 "M+": (Math.floor(time / 86400) % 12 + 1).toString(),
124 "d+": Math.floor(time / 86400).toString(),
125 "h+": Math.floor(time / 3600).toString(),
126 "m+": Math.floor((time % 3600) / 60).toString(),
127 "s+": (time % 60).toString(),
128 }
129 for (let k in o) {
130 const reg = new RegExp("(" + k + ")");
131 if (reg.test(format)) {
132 const count = format.match(reg)![0].length;
133 let str = ''
134 for (let i = 0; i < count; i++) {
135 str += '0'
136 }
137 format = format.replace(reg, (str + o[k]).substring(("" + o[k]).length));
138 }
139 }
140 return format;
141 }
142
143
144}
讲解145 行
字符串与文本展示工具人工通读

UtilityString.ts

提供空值安全的字符串读取、占位符格式化、打字机逐字显示与停止,以及按日期或秒数套用格式串生成时间文本。对话气泡、活动倒计时和文本模板都在使用这些方法。

先看 ReadNonEmptyString 与 Format 的边界,再看 TypewriterEffect 的 speed 单位,最后读两个日期格式化方法。

特殊处理与易错点

3注释UtilityString:安全读取非空字符串,避免把 undefined/null 转成字面量字符串。
5方法只有入参是字符串时才裁剪首尾空白后返回,其他类型一律返回空串。
15方法用正则把模板里的数字花括号占位符替换成对应下标参数,缺少参数时保留原占位符。
31方法清空 Label 后用 tween 按每字间隔逐字追加文本,全部显示后调用完成回调。
33注释清除之前的文字
36注释计算每个字符的间隔时间
39注释创建打字机效果
42注释使用tween创建打字机动画
50注释每个字符输入后调用回调
66方法传入 tween 实例时调用其 stop 停止逐字动画。
78方法把毫秒时间戳、可解析字符串或 Date 统一成 Date,再按年月日时分秒等占位符替换格式串。
120方法把秒数按天、时、分、秒换算后套用格式串,其中月份与日期并非真实日历值。