| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- import { _decorator, Component, Node } from 'cc';
- const { ccclass, property } = _decorator;
- interface evt {
- valueChange: (nowValue: number) => void
- }
- export class IncrementData {
- // 最大回体力
- private maxValue = 0
- // 回一点所需体力时间,单位毫秒
- private needTime = 5 * 60 * 1000
- // 上次恢复体力的时间,0代表当前时间
- private lastAddTime: number = 0
- // 当前默认值
- private _value: number=0
- private defValue: number = 0
- private _evt = chsdk.get_new_event<evt>();
- public get evt() {
- return this._evt
- }
- get value() {
- return this._value
- }
- set value(value: number) {
- this._value = value
- this.evt.emit("valueChange", value)
- }
- get needAddTime() {
- return this.lastAddTime + this.needTime
- }
- // 体力是否回满
- isMax(): boolean {
- if (!this.maxValue) return false
- return this.maxValue <= this.value
- }
- init(needTime: number, defValue: number = 0, maxValue?: number) {
- this.needTime = needTime
- this.maxValue = maxValue
- this.defValue = defValue
- }
- /**
- * 用于自定义,不会累加自带的value也没有最大值
- * @param num 当前时间的时间戳,单位到毫秒
- * @returns 计算增加值
- */
- useLastTime(num: number): number {
- if (!this.lastAddTime) {
- this.lastAddTime = num
- return 0
- }
- if (this.lastAddTime > num) {
- this.lastAddTime = num
- return 0
- }
- let difference = num - this.lastAddTime
- // 将时间差转化为秒
- let addValue = ~~(difference / this.needTime)
- if (addValue > 0) {
- // 更新lastTime
- this.lastAddTime = num - (difference % this.needTime)
- return addValue
- }
- return 0
- }
- /**
- *
- * @param time 当前时间的时间戳,单位到毫秒
- * @param value 当前结果
- * @returns 返回value累加时候的结果
- */
- addLastTime(time: number) {
- if (!this.maxValue) {
- return
- }
- let value = this.value
- if (value >= this.maxValue) {
- this.lastAddTime = time
- return value
- }
- if (!this.lastAddTime) {
- this.lastAddTime = time
- return value
- }
- if (this.lastAddTime > time) {
- this.lastAddTime = time
- return value
- }
- let difference = time - this.lastAddTime
- // 将时间差转化为秒
- let addValue = ~~(difference / this.needTime)
- if (addValue > 0) {
- // 更新lastTime
- let realAdd = Math.min(this.maxValue - value, addValue)
- if (realAdd < addValue) {
- this.lastAddTime = time - (difference % this.needTime)
- } else {
- this.lastAddTime = time
- }
- this.value = value + realAdd
- return value + realAdd
- }
- return value
- }
- serialize() {
- let data = {
- lastAddTime: this.lastAddTime,
- value:this.value
- }
- return data
- }
- unserialize(data: any) {
- debugger
- if (data) {
- this.lastAddTime = data.lastAddTime || 0
- this.value = data.value ?? this.defValue
- } else {
- this.lastAddTime = 0
- this.value = this.defValue
- }
- return this
- }
- }
|