NumberAnim.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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) {
  18. let time = new_value - this.targetProgress;
  19. this.targetProgress = new_value;
  20. this.PlayMoneyAni(0.3)
  21. }
  22. //////////////////////////////////数字滚动效果//////////////////////////////////
  23. /** 滚动的目标值 */
  24. private targetProgress: number = 0;
  25. private delta: number = 0;
  26. /** 滚动中的数字 */
  27. private curValue: number = 0;
  28. private curTime: number = 0;
  29. private totalTime: number = 0;
  30. /** 上次值 */
  31. private lastNum: number = 0;
  32. /** 动画中 */
  33. private isPlayAni: boolean = false;
  34. private PlayMoneyAni(time) {
  35. this.totalTime = time;
  36. this.delta = (this.targetProgress - this.lastNum) / time;
  37. this.curValue = this.lastNum;
  38. this.curTime = 0;
  39. // console.log("--->Update Time: " + time + " delta: " + this.delta + " curValue: " + this.curValue + " lastNum: " + this.lastNum);
  40. this.isPlayAni = true;
  41. }
  42. private PlayMoneyAniUpdate(dt) {
  43. if (this.isPlayAni) {
  44. if (this.curTime < this.totalTime) {
  45. this.curTime += dt;
  46. this.curValue += this.delta * dt;
  47. if (this.curValue >= this.targetProgress) {
  48. this.isPlayAni = false;
  49. this.curValue = this.targetProgress;
  50. this.lastNum = this.targetProgress;
  51. }
  52. // console.log("-->CurValue:" + this.curValue);
  53. } else {
  54. this.isPlayAni = false;
  55. this.curTime = this.totalTime;
  56. //this.unschedule(this.UpdateAni);
  57. this.curValue = this.targetProgress;
  58. this.lastNum = this.targetProgress;
  59. }
  60. if (this.curValue == this.targetProgress) {
  61. this.lbl_count.string = `${this.targetProgress}`;
  62. } else {
  63. this.lbl_count.string = `${this.curValue.toFixed(0)}`;
  64. }
  65. }
  66. }
  67. update(dt) {
  68. this.PlayMoneyAniUpdate(dt);
  69. }
  70. }