NumberAnim.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 (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: number) {
  41. this.totalTime = time;
  42. this.delta = (this.targetProgress - this.lastNum);// / time;
  43. this.curValue = this.lastNum;
  44. this.curTime = 0;
  45. this.isPlayAni = true;
  46. }
  47. private PlayMoneyAniUpdate(dt) {
  48. if (this.isPlayAni) {
  49. if (this.curTime < this.totalTime) {
  50. this.curTime += dt;
  51. this.curValue += this.delta * dt;
  52. if (this.curValue >= this.targetProgress) {
  53. this.isPlayAni = false;
  54. this.curValue = this.targetProgress;
  55. this.lastNum = this.targetProgress;
  56. }
  57. } else {
  58. this.isPlayAni = false;
  59. this.curTime = this.totalTime;
  60. this.curValue = this.targetProgress;
  61. this.lastNum = this.targetProgress;
  62. }
  63. if (this.curValue == this.targetProgress) {
  64. this.lbl_count.string = `${this.targetProgress}`;
  65. } else {
  66. if (!this.curValue) {
  67. mk.console.log('数字动画出现异常:', this.curValue);
  68. this.curValue = this.targetProgress;
  69. }
  70. this.lbl_count.string = this.curValue.toFixed(this.toFixed);
  71. }
  72. }
  73. }
  74. update(dt) {
  75. this.PlayMoneyAniUpdate(dt);
  76. }
  77. }