NumberAnim.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. this.toFixed = toFixed;
  19. this.len_target = new_value.toString().length;
  20. this.targetProgress = new_value;
  21. this.PlayMoneyAni(0.3)
  22. }
  23. //////////////////////////////////数字滚动效果//////////////////////////////////
  24. /** 滚动的目标值 */
  25. private targetProgress: number = 0;
  26. private delta: number = 0;
  27. /** 滚动中的数字 */
  28. private curValue: number = 0;
  29. private curTime: number = 0;
  30. private totalTime: number = 0;
  31. /** 上次值 */
  32. private lastNum: number = 0;
  33. /** 动画中 */
  34. private isPlayAni: boolean = false;
  35. /** 目标值长度 */
  36. private len_target: number = 0;
  37. /** 保留小数点位数 */
  38. private toFixed: number = 0;
  39. private PlayMoneyAni(time) {
  40. this.totalTime = time;
  41. this.delta = (this.targetProgress - this.lastNum) / time;
  42. this.curValue = this.lastNum;
  43. this.curTime = 0;
  44. // console.log("--->Update Time: " + time + " delta: " + this.delta + " curValue: " + this.curValue + " lastNum: " + this.lastNum);
  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. // console.log("-->CurValue:" + this.curValue);
  58. } else {
  59. this.isPlayAni = false;
  60. this.curTime = this.totalTime;
  61. //this.unschedule(this.UpdateAni);
  62. this.curValue = this.targetProgress;
  63. this.lastNum = this.targetProgress;
  64. }
  65. if (this.curValue == this.targetProgress) {
  66. this.lbl_count.string = `${this.targetProgress}`;
  67. } else {
  68. this.lbl_count.string = `${this.curValue.toFixed(this.toFixed)}`;
  69. }
  70. }
  71. }
  72. update(dt) {
  73. this.PlayMoneyAniUpdate(dt);
  74. }
  75. }