1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- import { _decorator, Component, Node, Label } from 'cc';
- import { StringUtil } from '../util/StringUtil';
- const { ccclass, property, requireComponent } = _decorator;
- @ccclass('RollingNumber')
- @requireComponent([Label])
- export class RollingNumber extends Component {
- private _text_lab: Label = null;
- private _current = 0; //当前值
- private _target = 0; //目标值
- private _duration = 0; //持续时间
- private _speed = 0; //动画速度
- private _playing = false; //动画是否播放
- private _limit = 0; //上限
- onLoad() {
- this._text_lab = this.getComponent(Label);
- this._text_lab.string = "0";
- }
- private _setValue(value: number) {
- this._current = value;
- this._text_lab.string = StringUtil.numberToTenThousand(value);
- }
- changeTo(target: number, duration: number = 1, limit: number = 999999) {
- this.stop();
- this._limit = limit;
- if (target > this._limit) {
- this._current = target;
- this._text_lab.string = StringUtil.numberToTenThousand(this._current);
- } else {
- if (duration > 0) {
- this._target = target;
- if (this._current - this._target == 1) {
- this._setValue(target);
- return;
- }
- this._duration = duration;
- this._speed = (this._target - this._current) / this._duration;
- this._playing = (target) ? true : false;
- } else {
- this._setValue(target);
- }
- }
- }
- addTo(value: number, duration: number = 1, limit: number = 999999) {
- this.stop();
- value = this._current + value;
- this.changeTo(value, duration, limit);
- }
- stop() {
- if (this._playing) {
- this._setValue(this._target);
- this._playing = false;
- this._target = -1;
- }
- }
- protected update(dt: number) {
- if (this._playing) {
- if (this._current == this._target) {
- this._playing = false;
- }
- let num = this._current + dt * this._speed;
- num = Math.ceil(num);
- if (this._over(num)) {
- num = this._target;
- this._playing = false;
- }
- this._setValue(num);
- }
- }
- private _over(num: number) {
- return (this._speed > 0) ? (num >= this._target) : (num <= this._target);
- }
- }
|