const { ccclass, property } = cc._decorator; /** * 数字跳动动画 * @author 薛鸿潇 */ @ccclass export default class NumberAnim extends cc.Component { /** 动画目标 */ private lbl_count: cc.Label = null; onLoad() { this.lbl_count = this.node.getComponent(cc.Label) || this.node.addComponent(cc.Label); } /** * 设置数值 * @param new_value 目标值 */ public setValue(new_value: number, toFixed: number = 0) { if (this.targetProgress == new_value) return; this.toFixed = toFixed; this.len_target = new_value.toString().length; this.targetProgress = new_value; this.PlayMoneyAni(0.3) } //////////////////////////////////数字滚动效果////////////////////////////////// /** 滚动的目标值 */ private targetProgress: number = 0; private delta: number = 0; /** 滚动中的数字 */ private curValue: number = 0; private curTime: number = 0; private totalTime: number = 0; /** 上次值 */ private lastNum: number = 0; /** 动画中 */ private isPlayAni: boolean = false; /** 目标值长度 */ private len_target: number = 0; /** 保留小数点位数 */ private toFixed: number = 0; private PlayMoneyAni(time) { this.totalTime = time; this.delta = (this.targetProgress - this.lastNum) / time; this.curValue = this.lastNum; this.curTime = 0; // console.log("--->Update Time: " + time + " delta: " + this.delta + " curValue: " + this.curValue + " lastNum: " + this.lastNum); this.isPlayAni = true; } private PlayMoneyAniUpdate(dt) { if (this.isPlayAni) { if (this.curTime < this.totalTime) { this.curTime += dt; this.curValue += this.delta * dt; if (this.curValue >= this.targetProgress) { this.isPlayAni = false; this.curValue = this.targetProgress; this.lastNum = this.targetProgress; } // console.log("-->CurValue:" + this.curValue); } else { this.isPlayAni = false; this.curTime = this.totalTime; //this.unschedule(this.UpdateAni); this.curValue = this.targetProgress; this.lastNum = this.targetProgress; } if (this.curValue == this.targetProgress) { this.lbl_count.string = `${this.targetProgress}`; } else { this.lbl_count.string = `${this.curValue.toFixed(this.toFixed)}`; } } } update(dt) { this.PlayMoneyAniUpdate(dt); } }