NumberAnim.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const { ccclass, property } = cc._decorator;
  2. /**
  3. * 数字跳动动画
  4. * @author 薛鸿潇
  5. */
  6. @ccclass
  7. export default class NumberAnim extends cc.Component {
  8. /** 动画目标 */
  9. private lbl_count: cc.Label = null;
  10. onLoad() {
  11. this.lbl_count = this.node.getComponent(cc.Label) || this.node.addComponent(cc.Label);
  12. }
  13. /**
  14. * 设置数值
  15. * @param new_value 目标值
  16. */
  17. public setValue(new_value: number, toFixed: number = 0) {
  18. if (!new_value || this.targetProgress == new_value) return;
  19. this.toFixed = toFixed;
  20. this.len_target = new_value.toString().length;
  21. this.targetProgress = new_value;
  22. this.PlayMoneyAni(0.3)
  23. }
  24. //////////////////////////////////数字滚动效果//////////////////////////////////
  25. /** 滚动的目标值 */
  26. private targetProgress: number = 0;
  27. private delta: number = 0;
  28. /** 滚动中的数字 */
  29. private curValue: number = 0;
  30. private curTime: number = 0;
  31. private totalTime: number = 0;
  32. /** 上次值 */
  33. private lastNum: number = 0;
  34. /** 动画中 */
  35. private isPlayAni: boolean = false;
  36. /** 目标值长度 */
  37. private len_target: number = 0;
  38. /** 保留小数点位数 */
  39. private toFixed: number = 0;
  40. private PlayMoneyAni(time) {
  41. this.totalTime = time;
  42. this.delta = (this.targetProgress - this.lastNum) / time;
  43. this.curValue = this.lastNum;
  44. this.curTime = 0;
  45. // console.log("--->Update Time: " + time + " delta: " + this.delta + " curValue: " + this.curValue + " lastNum: " + this.lastNum);
  46. this.isPlayAni = true;
  47. }
  48. private PlayMoneyAniUpdate(dt) {
  49. if (this.isPlayAni) {
  50. if (this.curTime < this.totalTime) {
  51. this.curTime += dt;
  52. this.curValue += this.delta * dt;
  53. if (this.curValue >= this.targetProgress) {
  54. this.isPlayAni = false;
  55. this.curValue = this.targetProgress;
  56. this.lastNum = this.targetProgress;
  57. }
  58. // console.log("-->CurValue:" + this.curValue);
  59. } else {
  60. this.isPlayAni = false;
  61. this.curTime = this.totalTime;
  62. //this.unschedule(this.UpdateAni);
  63. this.curValue = this.targetProgress;
  64. this.lastNum = this.targetProgress;
  65. }
  66. if (this.curValue == this.targetProgress) {
  67. this.lbl_count.string = `${this.targetProgress}`;
  68. } else {
  69. this.lbl_count.string = `${this.curValue.toFixed(this.toFixed)}`;
  70. }
  71. }
  72. }
  73. update(dt) {
  74. this.PlayMoneyAniUpdate(dt);
  75. }
  76. }