From 5937f2faf5d7c7be62cd7ea4549bfd71a53f9825 Mon Sep 17 00:00:00 2001 From: dgflash Date: Wed, 4 Sep 2024 21:23:53 +0800 Subject: [PATCH] =?UTF-8?q?1=E3=80=81=E4=BC=98=E5=8C=96=E8=AF=AD=E6=B3=95?= =?UTF-8?q?=202=E3=80=81=E4=BF=AE=E5=A4=8D=E6=9B=B4=E6=96=B0=E5=90=8E?= =?UTF-8?q?=E7=9A=84API=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/core/Root.ts | 12 +- assets/core/common/audio/AudioEffect.ts | 5 +- assets/core/common/audio/AudioManager.ts | 54 +++---- assets/core/common/audio/AudioMusic.ts | 1 + assets/core/common/event/MessageManager.ts | 8 +- assets/core/common/loader/ResLoader.ts | 13 +- assets/core/common/log/Logger.ts | 26 ++-- assets/core/common/random/RandomManager.ts | 8 +- assets/core/common/storage/StorageManager.ts | 10 +- assets/core/common/timer/TimerManager.ts | 4 +- assets/core/gui/GUI.ts | 12 +- assets/core/gui/layer/LayerDialog.ts | 2 +- assets/core/gui/layer/LayerManager.ts | 28 ++-- assets/core/gui/layer/LayerNotify.ts | 2 +- assets/core/gui/layer/LayerPopup.ts | 12 +- assets/core/gui/layer/LayerUI.ts | 19 ++- assets/core/utils/ArrayUtil.ts | 19 ++- assets/core/utils/CameraUtil.ts | 17 +-- assets/core/utils/JsonUtil.ts | 4 +- assets/core/utils/LayerUtil.ts | 4 +- assets/core/utils/MathUtil.ts | 12 +- assets/core/utils/PhysicsUtil.ts | 4 +- assets/core/utils/PlatformUtil.ts | 10 +- assets/core/utils/RotateUtil.ts | 20 +-- assets/core/utils/StringUtil.ts | 82 ++++------- assets/core/utils/TimeUtils.ts | 5 +- assets/core/utils/Vec3Util.ts | 135 ++++++++---------- assets/core/utils/ViewUtil.ts | 38 +++-- .../libs/animator-effect/Effect2DFollow3D.ts | 15 +- .../animator-effect/EffectFinishedRelease.ts | 2 +- .../libs/animator-effect/EffectSingleCase.ts | 16 +-- assets/libs/animator/AnimatorSpine.ts | 4 +- assets/libs/behavior-tree/BehaviorTree.ts | 10 +- assets/libs/behavior-tree/IControl.ts | 1 - assets/libs/collection/Collection.ts | 4 +- assets/libs/ecs/ECSEntity.ts | 4 +- assets/libs/ecs/ECSSystem.ts | 5 +- assets/libs/gui/label/LabelNumber.ts | 14 +- assets/libs/gui/label/LabelTime.ts | 2 +- assets/libs/gui/language/Language.ts | 11 +- assets/libs/gui/language/LanguageData.ts | 4 +- assets/libs/gui/language/LanguageLabel.ts | 6 +- assets/module/common/GameComponent.ts | 22 +-- assets/module/common/ModuleUtil.ts | 40 +++--- assets/module/config/BuildTimeConstants.ts | 2 +- assets/module/config/Config.ts | 6 +- assets/module/config/GameConfig.ts | 4 +- assets/module/config/GameQueryConfig.ts | 8 +- 48 files changed, 348 insertions(+), 398 deletions(-) diff --git a/assets/core/Root.ts b/assets/core/Root.ts index 10e0246..1318c9d 100644 --- a/assets/core/Root.ts +++ b/assets/core/Root.ts @@ -4,7 +4,7 @@ * @LastEditors: dgflash * @LastEditTime: 2023-08-28 10:02:57 */ -import { Component, Game, JsonAsset, Node, _decorator, director, game, screen, sys } from "cc"; +import { _decorator, Component, director, Game, game, JsonAsset, Node, screen, sys } from "cc"; import { GameConfig } from "../module/config/GameConfig"; import { GameQueryConfig } from "../module/config/GameQueryConfig"; import { oops, version } from "./Oops"; @@ -20,7 +20,7 @@ import { LayerManager } from "./gui/layer/LayerManager"; const { property } = _decorator; -var isInited = false; +let isInited = false; /** 框架显示层根节点 */ export class Root extends Component { @@ -47,7 +47,7 @@ export class Root extends Component { console.log(`Oops Framework v${version}`); this.enabled = false; - this.loadConfig(); + this.loadConfig().then(); } } @@ -99,7 +99,7 @@ export class Root extends Component { oops.res.release(config_name); } else { - this.loadConfig(); + this.loadConfig().then(); } } @@ -133,10 +133,10 @@ export class Root extends Component { game.on(Game.EVENT_HIDE, this.onHide, this); // 添加游戏界面屏幕自适应管理组件 - this.gui.addComponent(GUI)!; + this.gui.addComponent(GUI); // 游戏尺寸修改事件 - if (sys.isMobile == false) { + if (!sys.isMobile) { screen.on("window-resize", () => { oops.message.dispatchEvent(EventMessage.GAME_RESIZE); }, this); diff --git a/assets/core/common/audio/AudioEffect.ts b/assets/core/common/audio/AudioEffect.ts index 1a27531..ea3b016 100644 --- a/assets/core/common/audio/AudioEffect.ts +++ b/assets/core/common/audio/AudioEffect.ts @@ -46,6 +46,7 @@ export class AudioEffect extends AudioSource { * 加载音效并播放 * @param url 音效资源地址 * @param callback 资源加载完成并开始播放回调 + * @param bundleName 资源包名 */ load(url: string | AudioClip, callback?: Function, bundleName?: string) { if (bundleName == null) bundleName = oops.res.defaultBundleName; @@ -58,7 +59,7 @@ export class AudioEffect extends AudioSource { } else { // 地址加载音乐资源后播放 - if (this.effects.has(url) == false) { + if (!this.effects.has(url)) { oops.res.load(bundleName, url, AudioClip, (err: Error | null, data: AudioClip) => { if (err) { error(err); @@ -102,7 +103,7 @@ export class AudioEffect extends AudioSource { release(url: string | AudioClip, bundleName?: string) { if (bundleName == null) bundleName = oops.res.defaultBundleName; - var ac: AudioClip | undefined = undefined; + let ac: AudioClip | undefined = undefined; if (url instanceof AudioClip) { ac = url; if (this.effects.has(ac.uuid)) { diff --git a/assets/core/common/audio/AudioManager.ts b/assets/core/common/audio/AudioManager.ts index 6626506..22cd2cb 100644 --- a/assets/core/common/audio/AudioManager.ts +++ b/assets/core/common/audio/AudioManager.ts @@ -1,15 +1,15 @@ -import { AudioClip, Component } from "cc"; -import { oops } from "../../Oops"; -import { AudioEffect } from "./AudioEffect"; -import { AudioMusic } from "./AudioMusic"; +import {AudioClip, Component} from "cc"; +import {oops} from "../../Oops"; +import {AudioEffect} from "./AudioEffect"; +import {AudioMusic} from "./AudioMusic"; const LOCAL_STORE_KEY = "game_audio"; -/** +/** * 音频管理 - * @example -// 模块功能通过 oops.audio 调用 -oops.audio.playMusic("audios/nocturne"); + * @example + // 模块功能通过 oops.audio 调用 + oops.audio.playMusic("audios/nocturne"); */ export class AudioManager extends Component { /** 背景音乐管理对象 */ @@ -40,11 +40,12 @@ export class AudioManager extends Component { * 播放背景音乐 * @param url 资源地址 * @param callback 音乐播放完成事件 + * @param bundleName 资源包名 */ playMusic(url: string, callback?: Function, bundleName?: string) { if (this._switch_music) { this.music.loop = false; - this.music.load(url, callback, bundleName); + this.music.load(url, callback, bundleName).then(); } } @@ -52,7 +53,7 @@ export class AudioManager extends Component { playMusicLoop(url: string, bundleName?: string) { if (this._switch_music) { this.music.loop = true; - this.music.load(url, null!, bundleName); + this.music.load(url, null!, bundleName).then(); } } @@ -69,6 +70,7 @@ export class AudioManager extends Component { get progressMusic(): number { return this.music.progress; } + /** * 设置背景乐播放进度 * @param value 播放进度值 @@ -83,7 +85,8 @@ export class AudioManager extends Component { get volumeMusic(): number { return this._volume_music; } - /** + + /** * 设置背景音乐音量 * @param value 音乐音量值 */ @@ -92,26 +95,29 @@ export class AudioManager extends Component { this.music.volume = value; } - /** - * 获取背景音乐开关值 + /** + * 获取背景音乐开关值 */ get switchMusic(): boolean { return this._switch_music; } - /** + + /** * 设置背景音乐开关值 * @param value 开关值 */ set switchMusic(value: boolean) { this._switch_music = value; - if (value == false) + if (!value) this.music.stop(); } /** * 播放音效 * @param url 资源地址 + * @param callback 加载完成回调 + * @param bundleName 资源包名 */ playEffect(url: string | AudioClip, callback?: Function, bundleName?: string) { if (this._switch_effect) { @@ -124,12 +130,13 @@ export class AudioManager extends Component { this.effect.release(url, bundleName); } - /** - * 获取音效音量 + /** + * 获取音效音量 */ get volumeEffect(): number { return this._volume_effect; } + /** * 设置获取音效音量 * @param value 音效音量值 @@ -139,19 +146,20 @@ export class AudioManager extends Component { this.effect.volume = value; } - /** - * 获取音效开关值 + /** + * 获取音效开关值 */ get switchEffect(): boolean { return this._switch_effect; } + /** * 设置音效开关值 * @param value 音效开关值 */ set switchEffect(value: boolean) { this._switch_effect = value; - if (value == false) this.effect.stop(); + if (!value) this.effect.stop(); } /** 恢复当前暂停的音乐与音效播放 */ @@ -198,12 +206,10 @@ export class AudioManager extends Component { if (this.local_data) { try { this.setState(); - } - catch (e) { + } catch (e) { this.setStateDefault(); } - } - else { + } else { this.setStateDefault(); } diff --git a/assets/core/common/audio/AudioMusic.ts b/assets/core/common/audio/AudioMusic.ts index bddbd1a..d1e2d4d 100644 --- a/assets/core/common/audio/AudioMusic.ts +++ b/assets/core/common/audio/AudioMusic.ts @@ -44,6 +44,7 @@ export class AudioMusic extends AudioSource { * 加载音乐并播放 * @param url 音乐资源地址 * @param callback 加载完成回调 + * @param bundleName 资源包名 */ async load(url: string, callback?: Function, bundleName?: string) { if (bundleName == null) bundleName = oops.res.defaultBundleName; diff --git a/assets/core/common/event/MessageManager.ts b/assets/core/common/event/MessageManager.ts index 04074b2..b6b4f1d 100644 --- a/assets/core/common/event/MessageManager.ts +++ b/assets/core/common/event/MessageManager.ts @@ -48,8 +48,8 @@ export class MessageEventData { /** * 触发全局事件 - * @param event(string) 事件名 - * @param args(any) 事件参数 + * @param event 事件名 + * @param args 事件参数 */ dispatchEvent(event: string, ...args: any) { message.dispatchEvent(event, ...args); @@ -186,8 +186,8 @@ export class MessageManager { /** * 触发全局事件 - * @param event(string) 事件名 - * @param args(any) 事件参数 + * @param event 事件名 + * @param args 事件参数 */ dispatchEvent(event: string, ...args: any) { let list = this.events.get(event); diff --git a/assets/core/common/loader/ResLoader.ts b/assets/core/common/loader/ResLoader.ts index 09a5a6e..ddf5cbb 100644 --- a/assets/core/common/loader/ResLoader.ts +++ b/assets/core/common/loader/ResLoader.ts @@ -78,8 +78,8 @@ oops.res.loadRemote(this.url, opt, onComplete); loadRemote(url: string, options: IRemoteOptions | null, onComplete?: CompleteCallback | null): void; loadRemote(url: string, onComplete?: CompleteCallback | null): void; loadRemote(url: string, ...args: any): void { - var options: IRemoteOptions | null = null; - var onComplete: CompleteCallback | null = null; + let options: IRemoteOptions | null = null; + let onComplete: CompleteCallback | null = null; if (args.length == 2) { options = args[0]; onComplete = args[1]; @@ -93,7 +93,6 @@ oops.res.loadRemote(this.url, opt, onComplete); /** * 加载资源包 * @param url 资源地址 - * @param complete 完成事件 * @param v 资源MD5版本号 * @example var serverUrl = "http://192.168.1.8:8080/"; // 服务器地址 @@ -224,9 +223,9 @@ oops.res.loadDir("game", onProgressCallback, onCompleteCallback); release(path: string, bundleName?: string) { if (bundleName == null) bundleName = this.defaultBundleName; - var bundle = assetManager.getBundle(bundleName); + const bundle = assetManager.getBundle(bundleName); if (bundle) { - var asset = bundle.get(path); + const asset = bundle.get(path); if (asset) { this.releasePrefabtDepsRecursively(asset); } @@ -241,7 +240,7 @@ oops.res.loadDir("game", onProgressCallback, onCompleteCallback); releaseDir(path: string, bundleName?: string) { if (bundleName == null) bundleName = this.defaultBundleName; - var bundle: AssetManager.Bundle | null = assetManager.getBundle(bundleName); + const bundle: AssetManager.Bundle | null = assetManager.getBundle(bundleName); if (bundle) { var infos = bundle.getDirWithPath(path); if (infos) { @@ -263,7 +262,7 @@ oops.res.loadDir("game", onProgressCallback, onCompleteCallback); // assetManager.releaseAsset(uuid); } else { - var asset = assetManager.assets.get(uuid); + const asset = assetManager.assets.get(uuid); if (asset) { asset.decRef(); // assetManager.releaseAsset(asset); diff --git a/assets/core/common/log/Logger.ts b/assets/core/common/log/Logger.ts index b85667f..2043b6e 100644 --- a/assets/core/common/log/Logger.ts +++ b/assets/core/common/log/Logger.ts @@ -199,8 +199,8 @@ oops.log.table(object); return; } - var backLog = console.log || log; - var type = names[tag]; + const backLog = console.log || log; + const type = names[tag]; if (describe) { backLog.call(null, "%c%s%s%s:%s%o", color, this.getDateString(), '[' + type + ']', this.stack(5), describe, msg); } @@ -210,9 +210,9 @@ oops.log.table(object); } private static stack(index: number): string { - var e = new Error(); - var lines = e.stack!.split("\n"); - var result: Array = []; + const e = new Error(); + const lines = e.stack!.split("\n"); + const result: Array = []; lines.forEach((line) => { line = line.substring(7); var lineBreak = line.split(" "); @@ -224,22 +224,22 @@ oops.log.table(object); } }); - var list: string[] = []; - var splitList: Array = []; + let list: string[] = []; + let splitList: Array = []; if (index < result.length - 1) { - var value: string; - for (var a in result[index]) { - var splitList = a.split("."); + let value: string; + for (let a in result[index]) { + splitList = a.split("."); if (splitList.length == 2) { list = splitList.concat(); } else { value = result[index][a]; - var start = value!.lastIndexOf("/"); - var end = value!.lastIndexOf("."); + const start = value!.lastIndexOf("/"); + const end = value!.lastIndexOf("."); if (start > -1 && end > -1) { - var r = value!.substring(start + 1, end); + const r = value!.substring(start + 1, end); list.push(r); } else { diff --git a/assets/core/common/random/RandomManager.ts b/assets/core/common/random/RandomManager.ts index 455cde4..e24c687 100644 --- a/assets/core/common/random/RandomManager.ts +++ b/assets/core/common/random/RandomManager.ts @@ -27,7 +27,6 @@ export class RandomManager { * 生成指定范围的随机浮点数 * @param min 最小值 * @param max 最大值 - * @param type 类型 */ getRandomFloat(min: number = 0, max: number = 1): number { return this.getRandom() * (max - min) + min; @@ -69,7 +68,6 @@ export class RandomManager { * @param min 最小值 * @param max 最大值 * @param n 随机个数 - * @param type 类型 * @example var a = RandomManager.instance.getRandomByMinMaxList(50, 100, 5) console.log("随机的数字", a); @@ -111,9 +109,9 @@ export class RandomManager { console.log("定和随机分配", c); */ getRandomBySumList(n: number, sum: number): number[] { - var residue = sum; - var value = 0; - var result: Array = []; + let residue = sum; + let value = 0; + const result: Array = []; for (let i = 0; i < n; i++) { value = this.getRandomInt(0, residue, 3); if (i == n - 1) { diff --git a/assets/core/common/storage/StorageManager.ts b/assets/core/common/storage/StorageManager.ts index 2d902bd..aa62ff8 100644 --- a/assets/core/common/storage/StorageManager.ts +++ b/assets/core/common/storage/StorageManager.ts @@ -35,7 +35,7 @@ export class StorageManager { * @returns */ set(key: string, value: any) { - var keywords = this.getKey(key); + let keywords = this.getKey(key); if (null == key) { console.error("存储的key不能为空"); @@ -103,7 +103,7 @@ export class StorageManager { /** 获取指定关键字的数值 */ getNumber(key: string, defaultValue: number = 0): number { - var r = this.get(key); + const r = this.get(key); if (r == "0") { return Number(r); } @@ -112,13 +112,13 @@ export class StorageManager { /** 获取指定关键字的布尔值 */ getBoolean(key: string): boolean { - var r = this.get(key); + const r = this.get(key); return r.toLowerCase() === 'true'; } /** 获取指定关键字的JSON对象 */ getJson(key: string, defaultValue?: any): any { - var r = this.get(key); + const r = this.get(key); return (r && JSON.parse(r)) || defaultValue; } @@ -133,7 +133,7 @@ export class StorageManager { return; } - var keywords = this.getKey(key); + let keywords = this.getKey(key); if (this.encrypted) { keywords = EncryptUtil.md5(keywords); diff --git a/assets/core/common/timer/TimerManager.ts b/assets/core/common/timer/TimerManager.ts index 85e0e3a..cac4ff4 100644 --- a/assets/core/common/timer/TimerManager.ts +++ b/assets/core/common/timer/TimerManager.ts @@ -25,7 +25,7 @@ export class TimerManager extends Component { protected update(dt: number) { for (let key in this.times) { let data = this.times[key]; - var timer = data.timer as Timer; + let timer = data.timer as Timer; if (timer.update(dt)) { if (data.object[data.field] > 0) { data.object[data.field]--; @@ -77,7 +77,7 @@ export class TimerManager extends Component { } */ register(object: any, field: string, onSecond: Function, onComplete: Function): string { - var timer = new Timer(); + const timer = new Timer(); timer.step = 1; let data: any = {}; diff --git a/assets/core/gui/GUI.ts b/assets/core/gui/GUI.ts index 7de10ed..fc59d6a 100644 --- a/assets/core/gui/GUI.ts +++ b/assets/core/gui/GUI.ts @@ -44,7 +44,7 @@ export class GUI extends Component { /** 游戏画布尺寸变化 */ resize() { - var dr; + let dr; if (view.getDesignResolutionSize().width > view.getDesignResolutionSize().height) { dr = this.landscapeDrz; } @@ -52,11 +52,11 @@ export class GUI extends Component { dr = this.portraitDrz; } - var s = screen.windowSize; - var rw = s.width; - var rh = s.height; - var finalW = rw; - var finalH = rh; + const s = screen.windowSize; + const rw = s.width; + const rh = s.height; + let finalW = rw; + let finalH = rh; if ((rw / rh) > (dr.width / dr.height)) { // 如果更长,则用定高 diff --git a/assets/core/gui/layer/LayerDialog.ts b/assets/core/gui/layer/LayerDialog.ts index 650510b..36d8279 100644 --- a/assets/core/gui/layer/LayerDialog.ts +++ b/assets/core/gui/layer/LayerDialog.ts @@ -40,7 +40,7 @@ export class LayerDialog extends LayerPopUp { /** 显示模式弹窗 */ private show(config: UIConfig, params?: any, callbacks?: UICallbacks) { - var vp = this.ui_cache.get(config.prefab); + let vp = this.ui_cache.get(config.prefab); if (vp == null) { vp = new ViewParams(); vp.valid = true; diff --git a/assets/core/gui/layer/LayerManager.ts b/assets/core/gui/layer/LayerManager.ts index 0e21a9a..5ba4fd0 100644 --- a/assets/core/gui/layer/LayerManager.ts +++ b/assets/core/gui/layer/LayerManager.ts @@ -72,15 +72,15 @@ export class LayerManager { guide!: Node; /** 界面层 */ - private ui!: LayerUI; + private readonly ui!: LayerUI; /** 弹窗层 */ - private popup!: LayerPopUp; + private readonly popup!: LayerPopUp; /** 只能弹出一个的弹窗 */ - private dialog!: LayerDialog; + private readonly dialog!: LayerDialog; /** 游戏系统提示弹窗 */ - private system!: LayerDialog; + private readonly system!: LayerDialog; /** 消息提示控制器,请使用show方法来显示 */ - private notify!: LayerNotify; + private readonly notify!: LayerNotify; /** UI配置 */ private configs: { [key: number]: UIConfig } = {}; @@ -152,7 +152,7 @@ export class LayerManager { oops.gui.open(UIID.Loading, null, uic); */ open(uiId: number, uiArgs: any = null, callbacks?: UICallbacks): void { - var config = this.configs[uiId]; + const config = this.configs[uiId]; if (config == null) { warn(`打开编号为【${uiId}】的界面失败,配置信息不存在`); return; @@ -183,7 +183,7 @@ export class LayerManager { */ async openAsync(uiId: number, uiArgs: any = null): Promise { return new Promise((resolve, reject) => { - var callbacks: UICallbacks = { + const callbacks: UICallbacks = { onAdded: (node: Node, params: any) => { resolve(node); }, @@ -214,7 +214,7 @@ export class LayerManager { */ replaceAsync(removeUiId: number, openUiId: number, uiArgs: any = null): Promise { return new Promise(async (resolve, reject) => { - var node = await this.openAsync(openUiId, uiArgs); + const node = await this.openAsync(openUiId, uiArgs); if (node) { this.remove(removeUiId); resolve(node); @@ -232,7 +232,7 @@ export class LayerManager { * oops.gui.has(UIID.Loading); */ has(uiId: number): boolean { - var config = this.configs[uiId]; + const config = this.configs[uiId]; if (config == null) { warn(`编号为【${uiId}】的界面配置不存在,配置信息不存在`); return false; @@ -264,13 +264,13 @@ export class LayerManager { * oops.gui.has(UIID.Loading); */ get(uiId: number): Node { - var config = this.configs[uiId]; + const config = this.configs[uiId]; if (config == null) { warn(`编号为【${uiId}】的界面配置不存在,配置信息不存在`); return null!; } - var result: Node = null!; + let result: Node = null!; switch (config.layer) { case LayerType.UI: result = this.ui.get(config.prefab); @@ -296,7 +296,7 @@ export class LayerManager { * oops.gui.remove(UIID.Loading); */ remove(uiId: number, isDestroy?: boolean) { - var config = this.configs[uiId]; + const config = this.configs[uiId]; if (config == null) { warn(`删除编号为【${uiId}】的界面失败,配置信息不存在`); return; @@ -403,9 +403,9 @@ export class LayerManager { } private create_node(name: string) { - var node = new Node(name); + const node = new Node(name); node.layer = Layers.Enum.UI_2D; - var w: Widget = node.addComponent(Widget); + const w: Widget = node.addComponent(Widget); w.isAlignLeft = w.isAlignRight = w.isAlignTop = w.isAlignBottom = true; w.left = w.right = w.top = w.bottom = 0; w.alignMode = 2; diff --git a/assets/core/gui/layer/LayerNotify.ts b/assets/core/gui/layer/LayerNotify.ts index b63e14e..ab7e7b0 100644 --- a/assets/core/gui/layer/LayerNotify.ts +++ b/assets/core/gui/layer/LayerNotify.ts @@ -26,7 +26,7 @@ export class LayerNotify extends Node { constructor(name: string) { super(name); - var widget: Widget = this.addComponent(Widget); + const widget: Widget = this.addComponent(Widget); widget.isAlignLeft = widget.isAlignRight = widget.isAlignTop = widget.isAlignBottom = true; widget.left = widget.right = widget.top = widget.bottom = 0; widget.alignMode = 2; diff --git a/assets/core/gui/layer/LayerPopup.ts b/assets/core/gui/layer/LayerPopup.ts index f0f1e41..c8d6b51 100644 --- a/assets/core/gui/layer/LayerPopup.ts +++ b/assets/core/gui/layer/LayerPopup.ts @@ -31,7 +31,7 @@ export class LayerPopUp extends LayerUI { } protected async showUi(vp: ViewParams): Promise { - var r = await super.showUi(vp); + const r = await super.showUi(vp); if (r) { // 界面加载完成显示时,启动触摸非窗口区域关闭 this.openVacancyRemove(vp.config); @@ -62,9 +62,9 @@ export class LayerPopUp extends LayerUI { /** 关闭遮罩 */ protected closeMask() { if (this.mask == null) return; - - var flag = true; - for (var value of this.ui_nodes.values()) { + + let flag = true; + for (let value of this.ui_nodes.values()) { if (value.config.mask) { flag = false; break; @@ -94,8 +94,8 @@ export class LayerPopUp extends LayerUI { /** 关闭触摸非窗口区域关闭 */ protected closeVacancyRemove() { - var flag = true; - for (var value of this.ui_nodes.values()) { + let flag = true; + for (let value of this.ui_nodes.values()) { if (value.config.vacancy) { flag = false; break; diff --git a/assets/core/gui/layer/LayerUI.ts b/assets/core/gui/layer/LayerUI.ts index 68ebde9..5fdef7d 100644 --- a/assets/core/gui/layer/LayerUI.ts +++ b/assets/core/gui/layer/LayerUI.ts @@ -16,12 +16,11 @@ export class LayerUI extends Node { /** * UI基础层,允许添加多个预制件节点 * @param name 该层名 - * @param container 容器Node */ constructor(name: string) { super(name); - var widget: Widget = this.addComponent(Widget); + const widget: Widget = this.addComponent(Widget); widget.isAlignLeft = widget.isAlignRight = widget.isAlignTop = widget.isAlignBottom = true; widget.left = widget.right = widget.top = widget.bottom = 0; widget.alignMode = 2; @@ -30,7 +29,7 @@ export class LayerUI extends Node { /** * 添加一个预制件节点到层容器中,该方法将返回一个唯一`uuid`来标识该操作节点 - * @param prefabPath 预制件路径 + * @param config 界面配置数据 * @param params 自定义参数 * @param callbacks 回调函数对象,可选 * @returns ture为成功,false为失败 @@ -42,7 +41,7 @@ export class LayerUI extends Node { } // 检查缓存中是否存界面 - var vp = this.ui_cache.get(config.prefab); + let vp = this.ui_cache.get(config.prefab); if (vp == null) { vp = new ViewParams(); vp.config = config; @@ -139,11 +138,11 @@ export class LayerUI extends Node { * @param isDestroy 移除后是否释放 */ remove(prefabPath: string, isDestroy?: boolean): void { - var release = undefined; + let release = undefined; if (isDestroy !== undefined) release = isDestroy; // 界面移出舞台 - var vp = this.ui_nodes.get(prefabPath); + const vp = this.ui_nodes.get(prefabPath); if (vp) { // 优先使用参数中控制的释放条件,如果未传递参数则用配置中的释放条件,默认不缓存关闭的界面 if (release === undefined) { @@ -155,8 +154,8 @@ export class LayerUI extends Node { this.ui_cache.set(vp.config.prefab, vp); } - var childNode = vp.node; - var comp = childNode.getComponent(DelegateComponent)!; + const childNode = vp.node; + const comp = childNode.getComponent(DelegateComponent)!; comp.remove(release); } @@ -170,7 +169,7 @@ export class LayerUI extends Node { if (vp) { this.onCloseWindow(vp); this.ui_cache.delete(prefabPath); - var childNode = vp.node; + const childNode = vp.node; childNode.destroy(); } } @@ -180,7 +179,7 @@ export class LayerUI extends Node { * @param prefabPath 预制路径 */ get(prefabPath: string): Node { - var vp = this.ui_nodes.get(prefabPath); + const vp = this.ui_nodes.get(prefabPath); if (vp) return vp.node; return null!; diff --git a/assets/core/utils/ArrayUtil.ts b/assets/core/utils/ArrayUtil.ts index fbe2dcd..6add054 100644 --- a/assets/core/utils/ArrayUtil.ts +++ b/assets/core/utils/ArrayUtil.ts @@ -12,10 +12,10 @@ export class ArrayUtil { * @param arr 源数组 */ static noRepeated(arr: any[]) { - var res = [arr[0]]; - for (var i = 1; i < arr.length; i++) { - var repeat = false; - for (var j = 0; j < res.length; j++) { + const res = [arr[0]]; + for (let i = 1; i < arr.length; i++) { + let repeat = false; + for (let j = 0; j < res.length; j++) { if (arr[i] == res[j]) { repeat = true; break; @@ -61,8 +61,7 @@ export class ArrayUtil { * @param array 目标数组 */ static confound(array: []): any[] { - let result = array.slice().sort(() => Math.random() - .5); - return result; + return array.slice().sort(() => Math.random() - .5); } /** @@ -78,7 +77,7 @@ export class ArrayUtil { /** 删除数组中指定项 */ static removeItem(array: any[], item: any) { - var temp = array.concat(); + const temp = array.concat(); for (let i = 0; i < temp.length; i++) { const value = temp[i]; if (item == value) { @@ -94,8 +93,7 @@ export class ArrayUtil { * @param array2 目标数组2 */ static combineArrays(array1: any[], array2: any[]): any[] { - let newArray = [...array1, ...array2]; - return newArray; + return [...array1, ...array2]; } /** @@ -103,7 +101,6 @@ export class ArrayUtil { * @param array 目标数组 */ static getRandomValueInArray(array: any[]): any { - let newArray = array[Math.floor(Math.random() * array.length)]; - return newArray; + return array[Math.floor(Math.random() * array.length)]; } } diff --git a/assets/core/utils/CameraUtil.ts b/assets/core/utils/CameraUtil.ts index ccbe6e5..f343053 100644 --- a/assets/core/utils/CameraUtil.ts +++ b/assets/core/utils/CameraUtil.ts @@ -14,21 +14,18 @@ export class CameraUtil { * @param worldPos 坐标 */ static isInView(camera: Camera, worldPos: Vec3) { - var cameraPos = camera.node.getWorldPosition(); - var viewPos = camera.worldToScreen(worldPos); - var dir = Vec3.normalize(new Vec3(), worldPos.subtract(cameraPos)); - var forward = camera.node.forward; - var dot = Vec3.dot(forward, dir); + const cameraPos = camera.node.getWorldPosition(); + const viewPos = camera.worldToScreen(worldPos); + const dir = Vec3.normalize(new Vec3(), worldPos.subtract(cameraPos)); + const forward = camera.node.forward; + const dot = Vec3.dot(forward, dir); const viewportRect = view.getViewportRect(); // 判断物体是否在相机前面 - if (dot > 0 + return dot > 0 // 判断物体是否在视窗内 && (viewPos.x <= viewportRect.width) && (viewPos.x >= 0) - && (viewPos.y <= viewportRect.height) && (viewPos.y >= 0)) - return true; - else - return false; + && (viewPos.y <= viewportRect.height) && (viewPos.y >= 0); } } \ No newline at end of file diff --git a/assets/core/utils/JsonUtil.ts b/assets/core/utils/JsonUtil.ts index 55f1ddc..03778f9 100644 --- a/assets/core/utils/JsonUtil.ts +++ b/assets/core/utils/JsonUtil.ts @@ -34,7 +34,7 @@ export class JsonUtil { if (data.has(name)) callback(data.get(name)); else { - var url = path + name; + const url = path + name; resLoader.load(url, JsonAsset, (err: Error | null, content: JsonAsset) => { if (err) { console.warn(err.message); @@ -59,7 +59,7 @@ export class JsonUtil { resolve(data.get(name)) } else { - var url = path + name; + const url = path + name; resLoader.load(url, JsonAsset, (err: Error | null, content: JsonAsset) => { if (err) { console.warn(err.message); diff --git a/assets/core/utils/LayerUtil.ts b/assets/core/utils/LayerUtil.ts index be75c62..e6334d2 100644 --- a/assets/core/utils/LayerUtil.ts +++ b/assets/core/utils/LayerUtil.ts @@ -8,12 +8,12 @@ import { Node } from "cc"; /** 游戏摄像机层数据 */ export class LayerItem { - private _value: number; + private readonly _value: number; get value(): number { return this._value; } - private _name!: string; + private readonly _name!: string; get name(): string { return this._name; } diff --git a/assets/core/utils/MathUtil.ts b/assets/core/utils/MathUtil.ts index 446981a..819fad3 100644 --- a/assets/core/utils/MathUtil.ts +++ b/assets/core/utils/MathUtil.ts @@ -54,15 +54,15 @@ export class MathUtil { /** * 角度插值 - * @param angle1 角度1 - * @param angle2 角度2 - * @param t 时间 + * @param current 当前角度 + * @param target 目标角度 + * @param t 时间 */ static lerpAngle(current: number, target: number, t: number): number { current %= 360; target %= 360; - var dAngle: number = target - current; + const dAngle: number = target - current; if (dAngle > 180) { target = current - (360 - dAngle); @@ -84,7 +84,7 @@ export class MathUtil { current %= 360; target %= 360; - var dAngle: number = target - current; + const dAngle: number = target - current; if (dAngle > 180) { target = current - (360 - dAngle); @@ -93,7 +93,7 @@ export class MathUtil { target = current + (360 + dAngle); } - var dir = target - current; + const dir = target - current; if (speed > Math.abs(dir)) { return target; diff --git a/assets/core/utils/PhysicsUtil.ts b/assets/core/utils/PhysicsUtil.ts index 0488abf..f8406ce 100644 --- a/assets/core/utils/PhysicsUtil.ts +++ b/assets/core/utils/PhysicsUtil.ts @@ -8,13 +8,13 @@ import { Node } from "cc"; /** 物理分组数据 */ export class GroupItem { - private _value: number; + private readonly _value: number; /** 分组值 */ get value(): number { return this._value; } - private _name!: string; + private readonly _name!: string; /** 分组名 */ get name(): string { return this._name; diff --git a/assets/core/utils/PlatformUtil.ts b/assets/core/utils/PlatformUtil.ts index 7a0e72a..bf5e8f3 100644 --- a/assets/core/utils/PlatformUtil.ts +++ b/assets/core/utils/PlatformUtil.ts @@ -11,18 +11,16 @@ export class PlatformUtil { static isNativeAndroid() { if (typeof native == "undefined") return false - if (sys.isNative && sys.platform === sys.Platform.ANDROID) - return true - return false + return sys.isNative && sys.platform === sys.Platform.ANDROID; + } /** 是否为苹果系统 */ static isNativeIOS() { if (typeof native == "undefined") return false - if (sys.isNative && sys.os === sys.OS.IOS) - return true - return false + return sys.isNative && sys.os === sys.OS.IOS; + } /** 获取平台名 */ diff --git a/assets/core/utils/RotateUtil.ts b/assets/core/utils/RotateUtil.ts index 00b0f39..2691978 100644 --- a/assets/core/utils/RotateUtil.ts +++ b/assets/core/utils/RotateUtil.ts @@ -16,7 +16,7 @@ export class RotateUtil { * @param rad 旋转弧度 */ static rotateAround(target: Node, axis: Vec3, rad: number) { - var quat = new Quat(); + const quat = new Quat(); Quat.rotateAround(quat, target.getRotation(), axis.normalize(), rad); target.setRotation(quat); } @@ -27,17 +27,17 @@ export class RotateUtil { * 2、通过旋转中心点或当前目标点向量相减计算出移动方向 * 3、计算起始向量旋转后的向量 * 4、计算旋转后的坐标点 - * @param lookAt 瞄准目标 + * @param lookAt 瞄准目标 * @param target 旋转目标 * @param axis 围绕旋转的轴(例:Vec3.UP为Y轴) * @param rad 旋转弧度(例:delta.x * 1e-2) */ static rotateAroundTarget(lookAt: Node, target: Node, axis: Vec3, rad: number) { // 计算坐标 - var point_lookAt = lookAt.worldPosition; // 锚点坐标 - var point_target = target.worldPosition; // 目标坐标 - var quat = new Quat(); - var vec3 = new Vec3(); + const point_lookAt = lookAt.worldPosition; // 锚点坐标 + const point_target = target.worldPosition; // 目标坐标 + const quat = new Quat(); + const vec3 = new Vec3(); // 算出坐标点的旋转四元数 Quat.fromAxisAngle(quat, axis, rad); @@ -62,10 +62,10 @@ export class RotateUtil { * @param angle 角度 */ static circularEdgePosition(center: Vec3, radius: number, angle: number): Vec3 { - let edge = Vec3Util.z.multiplyScalar(radius); // 距离圆心Z抽的距离 - let dir = Vec3Util.sub(edge, center); // 初始圆心与目标位置的方向 - let vec3 = new Vec3(); - var quat = new Quat(); + const edge = Vec3Util.z.multiplyScalar(radius); // 距离圆心Z抽的距离 + const dir = Vec3Util.sub(edge, center); // 初始圆心与目标位置的方向 + const vec3 = new Vec3(); + const quat = new Quat(); // 算出坐标点的旋转四元数 Quat.fromAxisAngle(quat, Vec3.UP, toRadian(angle)); diff --git a/assets/core/utils/StringUtil.ts b/assets/core/utils/StringUtil.ts index c1c353d..bf1e6e8 100644 --- a/assets/core/utils/StringUtil.ts +++ b/assets/core/utils/StringUtil.ts @@ -22,7 +22,7 @@ export class StringUtil { return value.toLocaleString(); } - /** + /** * 转英文单位计数 * @param value 数字 * @param fixed 保留小数位数 @@ -30,19 +30,19 @@ export class StringUtil { * 12345 = 12.35K */ static numberToThousand(value: number, fixed: number = 2): string { - var k = 1000; - var sizes = ['', 'K', 'M', 'G']; + const k = 1000; + const sizes = ['', 'K', 'M', 'G']; if (value < k) { return value.toString(); } else { - var i = Math.floor(Math.log(value) / Math.log(k)); - var r = ((value / Math.pow(k, i))); + const i = Math.floor(Math.log(value) / Math.log(k)); + const r = ((value / Math.pow(k, i))); return r.toFixed(fixed) + sizes[i]; } } - /** + /** * 转中文单位计数 * @param value 数字 * @param fixed 保留小数位数 @@ -50,43 +50,17 @@ export class StringUtil { * 12345 = 1.23万 */ static numberToTenThousand(value: number, fixed: number = 2): string { - var k = 10000; - var sizes = ['', '万', '亿', '万亿']; + const k = 10000; + const sizes = ['', '万', '亿', '万亿']; if (value < k) { return value.toString(); } else { - var i = Math.floor(Math.log(value) / Math.log(k)); + const i = Math.floor(Math.log(value) / Math.log(k)); return ((value / Math.pow(k, i))).toFixed(fixed) + sizes[i]; } } - /** - * 时间格式化 - * @param date 时间对象 - * @param fmt 格式化字符(yyyy-MM-dd hh:mm:ss S) - */ - static format(date: Date, fmt: string) { - var o: any = { - "M+": date.getMonth() + 1, // 月份 - "d+": date.getDate(), // 日 - "h+": date.getHours(), // 小时 - "m+": date.getMinutes(), // 分 - "s+": date.getSeconds(), // 秒 - "q+": Math.floor((date.getMonth() + 3) / 3), // 季度 - "S": date.getMilliseconds() // 毫秒 - }; - if (/(y+)/.test(fmt)) { - fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); - } - for (var k in o) { - if (new RegExp("(" + k + ")").test(fmt)) { - fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); - } - } - return fmt; - } - /** * "," 分割字符串成数组 * @param str 字符串 @@ -98,8 +72,8 @@ export class StringUtil { return str.split(","); } - /** - * "|" 分割字符串成数组 + /** + * "|" 分割字符串成数组 * @param str 字符串 */ static stringToArray2(str: string) { @@ -109,7 +83,7 @@ export class StringUtil { return str.split("|"); } - /** + /** * ":" 分割字符串成数组 * @param str 字符串 */ @@ -120,8 +94,8 @@ export class StringUtil { return str.split(":"); } - /** - * ";" 分割字符串成数组 + /** + * ";" 分割字符串成数组 * @param str 字符串 */ static stringToArray4(str: string) { @@ -138,14 +112,15 @@ export class StringUtil { * @param showdot 是否把截取的部分用省略号代替 */ static sub(str: string, n: number, showdot: boolean = false) { - var r = /[^\x00-\xff]/g; + const r = /[^\x00-\xff]/g; if (str.replace(r, "mm").length <= n) { return str; } - var m = Math.floor(n / 2); - for (var i = m; i < str.length; i++) { + const m = Math.floor(n / 2); + for (let i = m; i < str.length; i++) { if (str.substr(0, i).replace(r, "mm").length >= n) { if (showdot) { return str.substr(0, i) + "..."; - } else { + } + else { return str.substr(0, i); } } @@ -158,8 +133,8 @@ export class StringUtil { * @param str 字符串 */ static stringLen(str: string) { - var realLength = 0, len = str.length, charCode = -1; - for (var i = 0; i < len; i++) { + let realLength = 0, len = str.length, charCode = -1; + for (let i = 0; i < len; i++) { charCode = str.charCodeAt(i); if (charCode >= 0 && charCode <= 128) realLength += 1; @@ -171,20 +146,17 @@ export class StringUtil { /** * 是否为空 - * @param str + * @param str */ public static IsEmpty(str: string): boolean { - if (str == null || str == undefined || str.length == 0) { - return true; - } - return false; + return str == null || str == undefined || str.length == 0; } /** * 参数替换 * @param str * @param rest - * + * * @example * * var str:string = "here is some info '{0}' and {1}"; @@ -195,8 +167,8 @@ export class StringUtil { public static substitute(str: string, ...rest: any[]): string { if (str == null) return ''; - var len: number = rest.length; - var args: any[]; + let len: number = rest.length; + let args: any[]; if (len == 1 && rest[0] instanceof Array) { args = rest[0]; len = args.length; @@ -205,7 +177,7 @@ export class StringUtil { args = rest; } - for (var i: number = 0; i < len; i++) { + for (let i: number = 0; i < len; i++) { str = str.replace(new RegExp("\\{" + i + "\\}", "g"), args[i]); } diff --git a/assets/core/utils/TimeUtils.ts b/assets/core/utils/TimeUtils.ts index 5bfef9a..11a2873 100644 --- a/assets/core/utils/TimeUtils.ts +++ b/assets/core/utils/TimeUtils.ts @@ -7,15 +7,14 @@ export class TimeUtil { * @returns */ public static daysBetween(time1: number | string | Date, time2: number | string | Date): number { - if (time2 == undefined || time2 == null) { + if (time2 == undefined) { time2 = +new Date(); } let startDate = new Date(time1).toLocaleDateString() let endDate = new Date(time2).toLocaleDateString() let startTime = new Date(startDate).getTime(); let endTime = new Date(endDate).getTime(); - let dates = Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24); - return dates; + return Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24); } /** 间隔秒数,时间顺序无要求,最后会获取绝对值 */ diff --git a/assets/core/utils/Vec3Util.ts b/assets/core/utils/Vec3Util.ts index e240d4b..9aeb5bd 100644 --- a/assets/core/utils/Vec3Util.ts +++ b/assets/core/utils/Vec3Util.ts @@ -1,6 +1,5 @@ - -import { Mat4, Vec3 } from "cc"; -import { MathUtil } from "./MathUtil"; +import {Mat4, Vec3} from "cc"; +import {MathUtil} from "./MathUtil"; /** 向量工具 */ export class Vec3Util { @@ -88,7 +87,7 @@ export class Vec3Util { * @param t 进度[0,1] */ static progress(start: Vec3, end: Vec3, t: number): Vec3 { - var current = new Vec3(); + const current = new Vec3(); current.x = MathUtil.progress(start.x, end.x, t); current.y = MathUtil.progress(start.y, end.y, t); current.z = MathUtil.progress(start.z, end.z, t); @@ -101,7 +100,7 @@ export class Vec3Util { * @param pos2 向量2 */ static add(pos1: Vec3, pos2: Vec3): Vec3 { - var outPos: Vec3 = new Vec3(); + const outPos: Vec3 = new Vec3(); Vec3.add(outPos, pos1, pos2); return outPos; } @@ -112,7 +111,7 @@ export class Vec3Util { * @param pos2 向量2 */ static sub(pos1: Vec3, pos2: Vec3): Vec3 { - var outPos: Vec3 = new Vec3(); + const outPos: Vec3 = new Vec3(); Vec3.subtract(outPos, pos1, pos2); return outPos; } @@ -123,7 +122,7 @@ export class Vec3Util { * @param scalar 常量 */ static mul(pos: Vec3, scalar: number): Vec3 { - var outPos: Vec3 = new Vec3(); + const outPos: Vec3 = new Vec3(); Vec3.multiplyScalar(outPos, pos, scalar); return outPos; } @@ -134,7 +133,7 @@ export class Vec3Util { * @param scalar 常量 */ static div(pos: Vec3, scalar: number): Vec3 { - var outPos: Vec3 = new Vec3(); + const outPos: Vec3 = new Vec3(); outPos.x = pos.x / scalar; outPos.y = pos.y / scalar; @@ -149,11 +148,7 @@ export class Vec3Util { * @param pos2 向量2 */ static equals(pos1: Vec3, pos2: Vec3): boolean { - if (pos1.x == pos2.x && pos1.y == pos2.y && pos1.z == pos2.z) { - return true; - } - - return false; + return pos1.x == pos2.x && pos1.y == pos2.y && pos1.z == pos2.z; } /** @@ -169,7 +164,7 @@ export class Vec3Util { * @param pos 向量 */ static normalize(pos: Vec3): Vec3 { - var outPos: Vec3 = new Vec3(pos.x, pos.y, pos.z); + const outPos: Vec3 = new Vec3(pos.x, pos.y, pos.z); return outPos.normalize(); } @@ -179,7 +174,7 @@ export class Vec3Util { * @param pos2 向量2 */ static direction(pos1: Vec3, pos2: Vec3): Vec3 { - var outPos: Vec3 = new Vec3(); + const outPos: Vec3 = new Vec3(); Vec3.subtract(outPos, pos2, pos1) return outPos.normalize(); } @@ -212,8 +207,7 @@ export class Vec3Util { static slerp(from: Vec3, to: Vec3, t: number): Vec3 { if (t <= 0) { return from; - } - else if (t >= 1) { + } else if (t >= 1) { return to; } @@ -235,12 +229,12 @@ export class Vec3Util { return to; } - var axis: Vec3 = new Vec3() // 获得旋转轴 + const axis: Vec3 = new Vec3(); // 获得旋转轴 Vec3.cross(axis, from, to); axis.normalize(); - var radian: number = angle * Math.PI / 180; // 获得弧度 - var rotateMatrix: Mat4 = new Mat4(); + const radian: number = angle * Math.PI / 180; // 获得弧度 + const rotateMatrix: Mat4 = new Mat4(); rotateMatrix.rotate(radian, axis); return new Vec3( @@ -252,16 +246,15 @@ export class Vec3Util { /** * 一次贝塞尔即为线性插值函数 - * @param t - * @param posStart - * @param posEnd - * @returns + * @param t + * @param posStart + * @param posEnd + * @returns */ static bezierOne(t: number, posStart: Vec3, posEnd: Vec3): Vec3 { if (t > 1) { t = 1; - } - else if (t < 0) { + } else if (t < 0) { t = 0 } @@ -273,28 +266,27 @@ export class Vec3Util { /** * 二次贝塞尔曲线 - * @param t - * @param posStart - * @param posCon - * @param posEnd - * @returns + * @param t + * @param posStart + * @param posCon + * @param posEnd + * @returns */ static bezierTwo(t: number, posStart: Vec3, posCon: Vec3, posEnd: Vec3): Vec3 { if (t > 1) { t = 1; - } - else if (t < 0) { + } else if (t < 0) { t = 0 } - var n = (1 - t); - var tt = t * t; + const n = (1 - t); + const tt = t * t; - var pStart: Vec3 = posStart.clone(); - var pos = new Vec3(); + const pStart: Vec3 = posStart.clone(); + const pos = new Vec3(); - var pCon: Vec3 = posCon.clone(); - var pEnd: Vec3 = posEnd.clone(); + const pCon: Vec3 = posCon.clone(); + const pEnd: Vec3 = posEnd.clone(); pos.add(pStart.multiplyScalar(n * n)); pos.add(pCon.multiplyScalar(2 * n * t)); @@ -305,33 +297,32 @@ export class Vec3Util { /** * 三次贝塞尔 - * @param t - * @param posStart - * @param posCon1 - * @param posCon2 - * @param posEnd - * @returns + * @param t + * @param posStart + * @param posCon1 + * @param posCon2 + * @param posEnd + * @returns */ static bezierThree(t: number, posStart: Vec3, posCon1: Vec3, posCon2: Vec3, posEnd: Vec3): Vec3 { if (t > 1) { t = 1; - } - else if (t < 0) { + } else if (t < 0) { t = 0 } - var n = (1 - t); - var nn = n * n; - var nnn = nn * n; - var tt = t * t; - var ttt = tt * t; + const n = (1 - t); + const nn = n * n; + const nnn = nn * n; + const tt = t * t; + const ttt = tt * t; - var pStart: Vec3 = posStart.clone(); - var pos = posStart.clone(); + const pStart: Vec3 = posStart.clone(); + const pos = posStart.clone(); - var pCon1: Vec3 = posCon1.clone(); - var pCon2: Vec3 = posCon2.clone(); - var pEnd: Vec3 = posEnd.clone(); + const pCon1: Vec3 = posCon1.clone(); + const pCon2: Vec3 = posCon2.clone(); + const pEnd: Vec3 = posEnd.clone(); pos.add(pStart.multiplyScalar(nnn)); pos.add(pCon1.multiplyScalar(3 * nn * t)); @@ -347,8 +338,8 @@ export class Vec3Util { * @param dir2 方向量2 */ static dot(dir1: Vec3, dir2: Vec3): number { - var tempDir1: Vec3 = dir1; - var tempDir2: Vec3 = dir2; + const tempDir1: Vec3 = dir1; + const tempDir2: Vec3 = dir2; return tempDir1.x * tempDir2.x + tempDir1.y * tempDir2.y + tempDir1.z * tempDir2.z; } @@ -359,16 +350,16 @@ export class Vec3Util { * @param dir2 方向量2 */ static cross(dir1: Vec3, dir2: Vec3): Vec3 { - var i: Vec3 = new Vec3(1, 0, 0); - var j: Vec3 = new Vec3(0, 1, 0); - var k: Vec3 = new Vec3(0, 0, 1); + const i: Vec3 = new Vec3(1, 0, 0); + const j: Vec3 = new Vec3(0, 1, 0); + const k: Vec3 = new Vec3(0, 0, 1); - var tempDir1: Vec3 = new Vec3(dir1.x, dir1.y, dir1.z); - var tempDir2: Vec3 = new Vec3(dir2.x, dir2.y, dir2.z); + const tempDir1: Vec3 = new Vec3(dir1.x, dir1.y, dir1.z); + const tempDir2: Vec3 = new Vec3(dir2.x, dir2.y, dir2.z); - var iv: Vec3 = i.multiplyScalar(tempDir1.y * tempDir2.z - tempDir2.y * tempDir1.z); - var jv: Vec3 = j.multiplyScalar(tempDir2.x * tempDir1.z - tempDir1.x * tempDir2.z); - var kv: Vec3 = k.multiplyScalar(tempDir1.x * tempDir2.y - tempDir2.x * tempDir1.y); + const iv: Vec3 = i.multiplyScalar(tempDir1.y * tempDir2.z - tempDir2.y * tempDir1.z); + const jv: Vec3 = j.multiplyScalar(tempDir2.x * tempDir1.z - tempDir1.x * tempDir2.z); + const kv: Vec3 = k.multiplyScalar(tempDir1.x * tempDir2.y - tempDir2.x * tempDir1.y); return iv.add(jv).add(kv); } @@ -379,7 +370,7 @@ export class Vec3Util { * @param dir2 方向量2 */ static angle(dir1: Vec3, dir2: Vec3): number { - var dotValue = this.dot(dir1.clone().normalize(), dir2.clone().normalize()); + const dotValue = this.dot(dir1.clone().normalize(), dir2.clone().normalize()); return Math.acos(dotValue) / Math.PI * 180 * Math.sign(dotValue); } @@ -389,11 +380,11 @@ export class Vec3Util { * @param b 角度b */ static dirAngle(a: Vec3, b: Vec3): number { - var c: Vec3 = Vec3Util.cross(a, b); - var angle: number = Vec3Util.angle(a, b); + const c: Vec3 = Vec3Util.cross(a, b); + const angle: number = Vec3Util.angle(a, b); // a 到 b 的夹角 - var sign = Math.sign(Vec3Util.dot(c.normalize(), Vec3Util.cross(b.normalize(), a.normalize()))); + const sign = Math.sign(Vec3Util.dot(c.normalize(), Vec3Util.cross(b.normalize(), a.normalize()))); return angle * sign; } -} +} \ No newline at end of file diff --git a/assets/core/utils/ViewUtil.ts b/assets/core/utils/ViewUtil.ts index 33a796e..a02b7a7 100644 --- a/assets/core/utils/ViewUtil.ts +++ b/assets/core/utils/ViewUtil.ts @@ -4,8 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2023-01-19 14:52:12 */ -import { Animation, AnimationClip, EventTouch, instantiate, Node, Prefab, Size, UITransform, v3, Vec3 } from "cc"; -import { resLoader } from "../common/loader/ResLoader"; +import {Animation, AnimationClip, EventTouch, instantiate, Node, Prefab, Size, UITransform, v3, Vec3} from "cc"; +import {resLoader} from "../common/loader/ResLoader"; /** 显示对象工具 */ export class ViewUtil { @@ -54,9 +54,8 @@ export class ViewUtil { * @param aPos A节点空间中的相对位置 */ static calculateASpaceToBSpacePos(a: Node, b: Node, aPos: Vec3): Vec3 { - var world: Vec3 = a.getComponent(UITransform)!.convertToWorldSpaceAR(aPos); - var space: Vec3 = b.getComponent(UITransform)!.convertToNodeSpaceAR(world); - return space; + const world: Vec3 = a.getComponent(UITransform)!.convertToWorldSpaceAR(aPos); + return b.getComponent(UITransform)!.convertToNodeSpaceAR(world); } /** @@ -65,10 +64,9 @@ export class ViewUtil { * @param space 转到此节点的坐标空间 */ static calculateScreenPosToSpacePos(event: EventTouch, space: Node): Vec3 { - let uil = event.getUILocation(); - let worldPos: Vec3 = v3(uil.x, uil.y); - let mapPos: Vec3 = space.getComponent(UITransform)!.convertToNodeSpaceAR(worldPos); - return mapPos; + const uil = event.getUILocation(); + const worldPos: Vec3 = v3(uil.x, uil.y); + return space.getComponent(UITransform)!.convertToNodeSpaceAR(worldPos); } /** @@ -79,12 +77,11 @@ export class ViewUtil { * @param defaultHeight 默认高 */ static uniformScale(targetWidth: number, targetHeight: number, defaultWidth: number, defaultHeight: number) { - var widthRatio = defaultWidth / targetWidth; - var heightRatio = defaultHeight / targetHeight; - var ratio; + const widthRatio = defaultWidth / targetWidth; + const heightRatio = defaultHeight / targetHeight; + let ratio; widthRatio < heightRatio ? ratio = widthRatio : ratio = heightRatio; - var size = new Size(Math.floor(targetWidth * ratio), Math.floor(targetHeight * ratio)); - return size; + return new Size(Math.floor(targetWidth * ratio), Math.floor(targetHeight * ratio)); } /** @@ -92,9 +89,8 @@ export class ViewUtil { * @param path 资源路径 */ static createPrefabNode(path: string): Node { - var p: Prefab = resLoader.get(path, Prefab)!; - var n = instantiate(p); - return n; + const p: Prefab = resLoader.get(path, Prefab)!; + return instantiate(p); } /** @@ -103,9 +99,9 @@ export class ViewUtil { */ static createPrefabNodeAsync(path: string): Promise { return new Promise(async (resolve, reject) => { - var prefab = await resLoader.loadAsync(path, Prefab) + const prefab = await resLoader.loadAsync(path, Prefab); if (prefab) { - var node = this.createPrefabNode(path); + const node = this.createPrefabNode(path); resolve(node); } else { @@ -126,12 +122,12 @@ export class ViewUtil { return; } - var anim = node.getComponent(Animation); + let anim = node.getComponent(Animation); if (anim == null) { anim = node.addComponent(Animation); } - var clip = resLoader.get(path, AnimationClip) as AnimationClip; + const clip = resLoader.get(path, AnimationClip) as AnimationClip; if (!clip) { return; } diff --git a/assets/libs/animator-effect/Effect2DFollow3D.ts b/assets/libs/animator-effect/Effect2DFollow3D.ts index 4c0f9e4..06293cc 100644 --- a/assets/libs/animator-effect/Effect2DFollow3D.ts +++ b/assets/libs/animator-effect/Effect2DFollow3D.ts @@ -5,9 +5,9 @@ * @LastEditTime: 2022-09-22 14:53:47 */ -import { Camera, Component, Node, Vec3, _decorator } from "cc"; -import { oops } from "../../core/Oops"; -import { MathUtil } from "../../core/utils/MathUtil"; +import {_decorator, Camera, Component, Node, Vec3} from "cc"; +import {oops} from "../../core/Oops"; +import {MathUtil} from "../../core/utils/MathUtil"; const { ccclass, property } = _decorator; @@ -40,12 +40,12 @@ export class Effect2DFollow3D extends Component { } start() { - var scale = this.zoom(); + const scale = this.zoom(); this.node.setScale(scale, scale, 1); } protected lateUpdate(dt: number) { - var scale = this.zoom(); + let scale = this.zoom(); scale = MathUtil.lerp(this.node.scale.x, scale, 0.1); this.node.setScale(scale, scale, 1); } @@ -56,9 +56,8 @@ export class Effect2DFollow3D extends Component { // @ts-ignore Vec3.transformMat4(this.pos, this.node3d.worldPosition, this.camera._camera!.matView); - var ratio = this.distance / Math.abs(this.pos.z); - var value = Math.floor(ratio * 100) / 100; - return value; + const ratio = this.distance / Math.abs(this.pos.z); + return Math.floor(ratio * 100) / 100; } } diff --git a/assets/libs/animator-effect/EffectFinishedRelease.ts b/assets/libs/animator-effect/EffectFinishedRelease.ts index 4127645..434090a 100644 --- a/assets/libs/animator-effect/EffectFinishedRelease.ts +++ b/assets/libs/animator-effect/EffectFinishedRelease.ts @@ -23,7 +23,7 @@ export class EffectFinishedRelease extends Component { if (spine) { // 播放第一个动画 let json = (spine.skeletonData!.skeletonJson! as any).animations; - for (var name in json) { + for (let name in json) { spine.setCompleteListener(this.onRecovery.bind(this)); spine.setAnimation(0, name, false); break; diff --git a/assets/libs/animator-effect/EffectSingleCase.ts b/assets/libs/animator-effect/EffectSingleCase.ts index 28d79d8..00fb790 100644 --- a/assets/libs/animator-effect/EffectSingleCase.ts +++ b/assets/libs/animator-effect/EffectSingleCase.ts @@ -27,7 +27,7 @@ export interface IEffectParams { bundleName?: string } -/** +/** * 动画特效对象池管理器,加载动画后自动播放,播放完后自动回收到池中 * 1、支持Spine动画 * 2、支持Cocos Animation动画 @@ -81,11 +81,11 @@ export class EffectSingleCase { return 0; } - /** + /** * 加载资源并生成节点对象 * @param path 预制资源路径 * @param parent 父节点 - * @param pos 位置 + * @param params 显示参数 */ async loadAndShow(path: string, parent?: Node, params?: IEffectParams): Promise { return new Promise(async (resolve, reject) => { @@ -110,11 +110,11 @@ export class EffectSingleCase { }); } - /** + /** * 显示预制对象 * @param path 预制资源路径 * @param parent 父节点 - * @param pos 位置 + * @param params 显示参数 */ private show(path: string, parent?: Node, params?: IEffectParams): Node { var np = this.effects.get(path); @@ -189,7 +189,7 @@ export class EffectSingleCase { /** * 释放对象池中显示对象的资源内存 - * @param path 资源路径 + * @param path 资源路径 */ release(path?: string) { if (path) { @@ -219,7 +219,7 @@ export class EffectSingleCase { } else { // COCOS动画 - var anims: Animation[] = node.getComponentsInChildren(Animation); + const anims: Animation[] = node.getComponentsInChildren(Animation); if (anims.length > 0) { anims.forEach(animator => { let aniName = animator.defaultClip?.name; @@ -233,7 +233,7 @@ export class EffectSingleCase { } // 粒子动画 else if (ParticleSystem) { - var particles: ParticleSystem[] = node.getComponentsInChildren(ParticleSystem); + const particles: ParticleSystem[] = node.getComponentsInChildren(ParticleSystem); particles.forEach(particle => { particle.simulationSpeed = this.speed; }); diff --git a/assets/libs/animator/AnimatorSpine.ts b/assets/libs/animator/AnimatorSpine.ts index dc276a4..98664bd 100644 --- a/assets/libs/animator/AnimatorSpine.ts +++ b/assets/libs/animator/AnimatorSpine.ts @@ -61,12 +61,12 @@ export default class AnimatorSpine extends AnimatorBase { /** ---------- 后续扩展代码 开始 ---------- */ public getBone(name: string): any { - var bone = this._spine.findBone(name); + const bone = this._spine.findBone(name); return bone } private onSpineEvent(trackEntry: any, event: any) { - var animationName = trackEntry.animation ? event.data.name : ""; + const animationName = trackEntry.animation ? event.data.name : ""; this._animationPlayer?.onFrameEventCallback(animationName, this); } diff --git a/assets/libs/behavior-tree/BehaviorTree.ts b/assets/libs/behavior-tree/BehaviorTree.ts index 81d922d..55f78dc 100644 --- a/assets/libs/behavior-tree/BehaviorTree.ts +++ b/assets/libs/behavior-tree/BehaviorTree.ts @@ -1,14 +1,14 @@ import { BTreeNode } from './BTreeNode'; import { IControl } from './IControl'; -var countUnnamed = 0; +let countUnnamed = 0; /** 行为树 */ export class BehaviorTree implements IControl { - private title: string; + private readonly title: string; /** 根节点 */ - private _root: BTreeNode; + private readonly _root: BTreeNode; /** 当前执行节点 */ private _current!: BTreeNode; /** 是否已开始执行 */ @@ -45,7 +45,7 @@ export class BehaviorTree implements IControl { } this._started = true; - var node = BehaviorTree.getNode(this._root); + const node = BehaviorTree.getNode(this._root); this._current = node; node.setControl(this); node.start(this._blackboard); @@ -75,7 +75,7 @@ export class BehaviorTree implements IControl { } static getNode(name: string | BTreeNode): BTreeNode { - var node = name instanceof BTreeNode ? name : this._registeredNodes.get(name); + const node = name instanceof BTreeNode ? name : this._registeredNodes.get(name); if (!node) { throw new Error(`无法找到节点【${name}】,可能它没有注册过`); } diff --git a/assets/libs/behavior-tree/IControl.ts b/assets/libs/behavior-tree/IControl.ts index 4cbff1d..5312536 100644 --- a/assets/libs/behavior-tree/IControl.ts +++ b/assets/libs/behavior-tree/IControl.ts @@ -17,5 +17,4 @@ export interface IControl { /** 正在处理中 */ running(blackboard?: any): void; - } \ No newline at end of file diff --git a/assets/libs/collection/Collection.ts b/assets/libs/collection/Collection.ts index 6b767e0..c446cf0 100644 --- a/assets/libs/collection/Collection.ts +++ b/assets/libs/collection/Collection.ts @@ -37,9 +37,9 @@ export class Collection extends Map{ * @param key 关键字 */ delete(key: K): boolean { - var value = this.get(key); + const value = this.get(key); if (value) { - var index = this._array.indexOf(value); + const index = this._array.indexOf(value); if (index > -1) this._array.splice(index, 1); return super.delete(key); } diff --git a/assets/libs/ecs/ECSEntity.ts b/assets/libs/ecs/ECSEntity.ts index 2879d61..c801019 100644 --- a/assets/libs/ecs/ECSEntity.ts +++ b/assets/libs/ecs/ECSEntity.ts @@ -25,7 +25,7 @@ function broadcastCompAddOrRemove(entity: ECSEntity, componentTypeId: number) { * @param ctor */ function createComp(ctor: CompCtor): T { - var cct = ECSModel.compCtors[ctor.tid]; + const cct = ECSModel.compCtors[ctor.tid]; if (!cct) { throw Error(`没有找到该组件的构造函数,检查${ctor.compName}是否为不可构造的组件`); } @@ -42,7 +42,7 @@ function createComp(ctor: CompCtor): T { */ function destroyEntity(entity: ECSEntity) { if (ECSModel.eid2Entity.has(entity.eid)) { - var entitys = ECSModel.entityPool.get(entity.name); + let entitys = ECSModel.entityPool.get(entity.name); if (entitys == null) { entitys = []; ECSModel.entityPool.set(entity.name, entitys); diff --git a/assets/libs/ecs/ECSSystem.ts b/assets/libs/ecs/ECSSystem.ts index fb71d06..fdfb70f 100644 --- a/assets/libs/ecs/ECSSystem.ts +++ b/assets/libs/ecs/ECSSystem.ts @@ -122,9 +122,10 @@ export abstract class ECSComblockSystem { * @returns */ private execute1(dt: number): void { + let entities; if (this.removedEntities.size > 0) { if (this.hasEntityRemove) { - var entities = this.removedEntities.values(); + entities = this.removedEntities.values(); for (let entity of entities) { (this as unknown as ecs.IEntityRemoveSystem).entityRemove(entity); } @@ -139,7 +140,7 @@ export abstract class ECSComblockSystem { // 处理刚进来的实体 if (this.enteredEntities!.size > 0) { if (this.hasEntityEnter) { - var entities = this.enteredEntities!.values(); + entities = this.enteredEntities!.values(); for (let entity of entities) { (this as unknown as ecs.IEntityEnterSystem).entityEnter(entity); } diff --git a/assets/libs/gui/label/LabelNumber.ts b/assets/libs/gui/label/LabelNumber.ts index 158a8c5..863d3de 100644 --- a/assets/libs/gui/label/LabelNumber.ts +++ b/assets/libs/gui/label/LabelNumber.ts @@ -4,26 +4,27 @@ * @LastEditors: dgflash * @LastEditTime: 2023-08-11 10:27:04 */ -import { Label, _decorator, error } from "cc"; +import {Label, _decorator, error} from "cc"; -const { ccclass, property, menu } = _decorator; +const {ccclass, property, menu} = _decorator; /** 只能显示数字的标签组件 */ @ccclass("LabelNumber") @menu('ui/label/LabelNumber') export default class LabelNumber extends Label { - @property({ tooltip: "数字" }) + @property({tooltip: "数字"}) _num: number = 0; - @property({ tooltip: "数字" }) + @property({tooltip: "数字"}) get num(): number { return this._num; } + set num(value: number) { this._num = value; this.updateLabel(); } - @property({ tooltip: "货币符号" }) + @property({tooltip: "货币符号"}) symbol: string = ""; start() { @@ -32,9 +33,6 @@ export default class LabelNumber extends Label { /** 刷新文本 */ protected updateLabel() { - if (typeof (this._num) != "number") { - error("[LabelNumber] num不是一个合法数字"); - } this.string = this.num.toString() + this.symbol; } } \ No newline at end of file diff --git a/assets/libs/gui/label/LabelTime.ts b/assets/libs/gui/label/LabelTime.ts index 8e8b2d1..a5b0030 100644 --- a/assets/libs/gui/label/LabelTime.ts +++ b/assets/libs/gui/label/LabelTime.ts @@ -146,7 +146,7 @@ export default class LabelTime extends Label { } private onGameShow() { - var interval = Math.floor((oops.timer.getTime() - (this.backStartTime || oops.timer.getTime())) / 1000); + const interval = Math.floor((oops.timer.getTime() - (this.backStartTime || oops.timer.getTime())) / 1000); this.countDown -= interval; if (this.countDown < 0) { this.countDown = 0; diff --git a/assets/libs/gui/language/Language.ts b/assets/libs/gui/language/Language.ts index 5128a81..29eed4b 100644 --- a/assets/libs/gui/language/Language.ts +++ b/assets/libs/gui/language/Language.ts @@ -1,6 +1,6 @@ -import { Logger } from "../../../core/common/log/Logger"; -import { LanguageData } from "./LanguageData"; -import { LanguagePack } from "./LanguagePack"; +import {Logger} from "../../../core/common/log/Logger"; +import {LanguageData} from "./LanguageData"; +import {LanguagePack} from "./LanguagePack"; /** 多语言管理器 */ export class LanguageManager { @@ -44,8 +44,7 @@ export class LanguageManager { getNextLang(): string { let supportLangs = this.languages; let index = supportLangs.indexOf(LanguageData.current); - let newLanguage = supportLangs[(index + 1) % supportLangs.length]; - return newLanguage; + return supportLangs[(index + 1) % supportLangs.length]; } /** @@ -74,7 +73,7 @@ export class LanguageManager { this.loadLanguageAssets(language, (lang: string) => { Logger.logConfig(`当前语言为【${language}】`); - var oldLanguage = LanguageData.current; + const oldLanguage = LanguageData.current; LanguageData.current = language; this._languagePack.updateLanguage(language); this._languagePack.releaseLanguageAssets(oldLanguage); diff --git a/assets/libs/gui/language/LanguageData.ts b/assets/libs/gui/language/LanguageData.ts index ff469c8..66bf54e 100644 --- a/assets/libs/gui/language/LanguageData.ts +++ b/assets/libs/gui/language/LanguageData.ts @@ -35,13 +35,13 @@ export class LanguageData { * 3、config/game/Language配置表使用oops-plugin-excel-to-json插件生成,点击项目根目录下载update-oops-plugin-framework.bat或update-oops-plugin-framework.sh脚本下载插件 */ public static getLangByID(labId: string): string { - var text = this.json[labId]; + const text = this.json[labId]; if (text) { return text; } if (this.excel) { - var record = this.excel[labId]; + const record = this.excel[labId]; if (record) { return record[this.current]; } diff --git a/assets/libs/gui/language/LanguageLabel.ts b/assets/libs/gui/language/LanguageLabel.ts index 1fee3d6..8e2426b 100644 --- a/assets/libs/gui/language/LanguageLabel.ts +++ b/assets/libs/gui/language/LanguageLabel.ts @@ -106,9 +106,9 @@ export class LanguageLabel extends Component { } updateContent() { - var label = this.getComponent(Label); - var richtext = this.getComponent(RichText); - var font: TTFFont | null = LanguageData.font + const label = this.getComponent(Label); + const richtext = this.getComponent(RichText); + const font: TTFFont | null = LanguageData.font; if (label) { if (font) { diff --git a/assets/module/common/GameComponent.ts b/assets/module/common/GameComponent.ts index ea1d025..6977e67 100644 --- a/assets/module/common/GameComponent.ts +++ b/assets/module/common/GameComponent.ts @@ -245,7 +245,7 @@ export class GameComponent extends Component { /** 释放一个资源 */ release() { if (this.resPaths) { - var rps = this.resPaths.get(ResType.Load); + const rps = this.resPaths.get(ResType.Load); if (rps) { rps.forEach((value: ResRecord) => { oops.res.release(value.path, value.bundle); @@ -258,7 +258,7 @@ export class GameComponent extends Component { /** 释放一个文件夹的资源 */ releaseDir() { if (this.resPaths) { - var rps = this.resPaths.get(ResType.LoadDir); + const rps = this.resPaths.get(ResType.LoadDir); if (rps) { rps.forEach((value: ResRecord) => { oops.res.releaseDir(value.path, value.bundle); @@ -270,7 +270,7 @@ export class GameComponent extends Component { /** 释放音效资源 */ releaseAudioEffect() { if (this.resPaths) { - var rps = this.resPaths.get(ResType.Audio); + const rps = this.resPaths.get(ResType.Audio); if (rps) { rps.forEach((value: ResRecord) => { oops.audio.releaseEffect(value.path, value.bundle); @@ -327,8 +327,8 @@ export class GameComponent extends Component { protected setButton() { // 自定义按钮批量绑定触摸事件 this.node.on(Node.EventType.TOUCH_END, (event: EventTouch) => { - var self: any = this; - var func = self[event.target.name]; + const self: any = this; + const func = self[event.target.name]; if (func) { func.call(this, event); } @@ -340,13 +340,13 @@ export class GameComponent extends Component { // Cocos Creator Button组件批量绑定触摸事件(使用UIButton支持放连点功能) const regex = /<([^>]+)>/; - var buttons = this.node.getComponentsInChildren