RollingNumber.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { _decorator, Component, Node, Label } from 'cc';
  2. import { StringUtil } from '../util/StringUtil';
  3. const { ccclass, property, requireComponent } = _decorator;
  4. @ccclass('RollingNumber')
  5. @requireComponent([Label])
  6. export class RollingNumber extends Component {
  7. private _text_lab: Label = null;
  8. private _current = 0; //当前值
  9. private _target = 0; //目标值
  10. private _duration = 0; //持续时间
  11. private _speed = 0; //动画速度
  12. private _playing = false; //动画是否播放
  13. private _limit = 0; //上限
  14. onLoad() {
  15. this._text_lab = this.getComponent(Label);
  16. this._text_lab.string = "0";
  17. }
  18. private _setValue(value: number) {
  19. this._current = value;
  20. this._text_lab.string = StringUtil.numberToTenThousand(value);
  21. }
  22. changeTo(target: number, duration: number = 1, limit: number = 999999) {
  23. this.stop();
  24. this._limit = limit;
  25. if (target > this._limit) {
  26. this._current = target;
  27. this._text_lab.string = StringUtil.numberToTenThousand(this._current);
  28. } else {
  29. if (duration > 0) {
  30. this._target = target;
  31. if (this._current - this._target == 1) {
  32. this._setValue(target);
  33. return;
  34. }
  35. this._duration = duration;
  36. this._speed = (this._target - this._current) / this._duration;
  37. this._playing = (target) ? true : false;
  38. } else {
  39. this._setValue(target);
  40. }
  41. }
  42. }
  43. addTo(value: number, duration: number = 1, limit: number = 999999) {
  44. this.stop();
  45. value = this._current + value;
  46. this.changeTo(value, duration, limit);
  47. }
  48. stop() {
  49. if (this._playing) {
  50. this._setValue(this._target);
  51. this._playing = false;
  52. this._target = -1;
  53. }
  54. }
  55. protected update(dt: number) {
  56. if (this._playing) {
  57. if (this._current == this._target) {
  58. this._playing = false;
  59. }
  60. let num = this._current + dt * this._speed;
  61. num = Math.ceil(num);
  62. if (this._over(num)) {
  63. num = this._target;
  64. this._playing = false;
  65. }
  66. this._setValue(num);
  67. }
  68. }
  69. private _over(num: number) {
  70. return (this._speed > 0) ? (num >= this._target) : (num <= this._target);
  71. }
  72. }