分享一个数字文字横向滚动效果

1.只支持数字文字横向滚动,从开始数字到目标数字,间隔时长
2.使用时将脚本绑定在Label上调用 SetData 函数就可以了

代码如下:
import { _decorator, Component, Node, Label } from ‘cc’;
const { ccclass, property } = _decorator;
@ccclass(‘NumberScroll’)
export class NumberScroll extends Component {
isPlayAnim:Boolean = false;

start_num:number = 0; //开始数字
end_num:number = 0;   //结束数字
src_number:number = 0;
add:number = 0;  //总想加数量
temp_num = 0; //当前显示
callback = null; //回调

interval = 0.05; // 每隔50ms更新一次数值
dt = 0
stratTime = 0
endTime = 0

start() {
    
}

//将数字用逗号分隔
GetChangeNumber(num:number):string {
    let formattedNum: string = new Intl.NumberFormat().format(num);
    return formattedNum
}

//设置数字
SetData(end_num:number, start_num:number, duration: number, interval:number, callback: (value: number) => void){

    if (null == interval){interval = this.interval}
    this.interval = interval

    this.start_num = start_num
    const steps = duration / this.interval;                  // 计算需要更新多少次数值
    this.add = (Math.abs(end_num - start_num)) / steps       // 计算每步增加多少数值
    this.temp_num = this.start_num                           // 当前数值初始化为起始数值

    this.callback = callback
    this.SetStringLabel(this.temp_num)

    this.end_num = end_num
    this.stratTime = new Date().getTime()
    this.isPlayAnim = true
}

SetStringLabel(number){
    let node = this.node.getComponent(Label);
    node.string = this.GetChangeNumber(number)
}

SetStringLabelNull(){
    let node = this.node.getComponent(Label);
    node.string = ""
}

//定時器刷新
refreshTime(){
    if(!this.isPlayAnim) return;
    if(this.start_num > this.end_num){
        this.temp_num -= this.add
    }else{
        this.temp_num += this.add
    }

    if (Math.abs(this.end_num - this.temp_num) <= Math.abs(this.add))  {
        this.isPlayAnim = false
        this.temp_num = this.end_num
        
        if (this.callback){
            this.callback(this.end_num)
        }

        this.endTime = new Date().getTime()
        console.log("時常=",this.stratTime,this.endTime,(this.endTime - this.stratTime) / 1000)
    }
    this.SetStringLabel(this.temp_num)
}



update(deltaTime: number) {
    if(!this.isPlayAnim) return;
    this.dt += deltaTime
    if (this.interval > this.dt) return;
    this.dt = 0

    this.refreshTime()
}

}
}

上图看看呗