1、优化语法

2、修复更新后的API注释
This commit is contained in:
dgflash
2024-09-04 21:23:53 +08:00
parent 7482f61d6c
commit 5937f2faf5
48 changed files with 348 additions and 398 deletions

View File

@@ -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);

View File

@@ -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)) {

View File

@@ -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();
}

View File

@@ -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;

View File

@@ -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);

View File

@@ -78,8 +78,8 @@ oops.res.loadRemote<ImageAsset>(this.url, opt, onComplete);
loadRemote<T extends Asset>(url: string, options: IRemoteOptions | null, onComplete?: CompleteCallback<T> | null): void;
loadRemote<T extends Asset>(url: string, onComplete?: CompleteCallback<T> | null): void;
loadRemote<T extends Asset>(url: string, ...args: any): void {
var options: IRemoteOptions | null = null;
var onComplete: CompleteCallback<T> | null = null;
let options: IRemoteOptions | null = null;
let onComplete: CompleteCallback<T> | null = null;
if (args.length == 2) {
options = args[0];
onComplete = args[1];
@@ -93,7 +93,6 @@ oops.res.loadRemote<ImageAsset>(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);

View File

@@ -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<any> = [];
const e = new Error();
const lines = e.stack!.split("\n");
const result: Array<any> = [];
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<string> = [];
let list: string[] = [];
let splitList: Array<string> = [];
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 {

View File

@@ -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<number> = [];
let residue = sum;
let value = 0;
const result: Array<number> = [];
for (let i = 0; i < n; i++) {
value = this.getRandomInt(0, residue, 3);
if (i == n - 1) {

View File

@@ -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);

View File

@@ -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 = {};

View File

@@ -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)) {
// 如果更长,则用定高

View File

@@ -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;

View File

@@ -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<Node | null> {
return new Promise<Node | null>((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<Node | null> {
return new Promise<Node | null>(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;

View File

@@ -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;

View File

@@ -31,7 +31,7 @@ export class LayerPopUp extends LayerUI {
}
protected async showUi(vp: ViewParams): Promise<boolean> {
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;

View File

@@ -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!;

View File

@@ -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)];
}
}

View File

@@ -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);
}
}

View File

@@ -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);

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -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;

View File

@@ -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;
}
/** 获取平台名 */

View File

@@ -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));

View File

@@ -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]);
}

View File

@@ -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);
}
/** 间隔秒数,时间顺序无要求,最后会获取绝对值 */

View File

@@ -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 进度[01]
*/
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;
}
}
}

View File

@@ -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<Node> {
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;
}

View File

@@ -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;
}
}

View File

@@ -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;

View File

@@ -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<Node> {
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;
});

View File

@@ -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);
}

View File

@@ -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}】,可能它没有注册过`);
}

View File

@@ -17,5 +17,4 @@ export interface IControl {
/** 正在处理中 */
running(blackboard?: any): void;
}

View File

@@ -37,9 +37,9 @@ export class Collection<K, V> extends Map<K, V>{
* @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);
}

View File

@@ -25,7 +25,7 @@ function broadcastCompAddOrRemove(entity: ECSEntity, componentTypeId: number) {
* @param ctor
*/
function createComp<T extends ecs.IComp>(ctor: CompCtor<T>): 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<T extends ecs.IComp>(ctor: CompCtor<T>): 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);

View File

@@ -122,9 +122,10 @@ export abstract class ECSComblockSystem<E extends ECSEntity = ECSEntity> {
* @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<E extends ECSEntity = ECSEntity> {
// 处理刚进来的实体
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);
}

View File

@@ -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;
}
}

View File

@@ -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;

View File

@@ -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);

View File

@@ -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];
}

View File

@@ -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) {

View File

@@ -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<Button>(Button);
const buttons = this.node.getComponentsInChildren<Button>(Button);
buttons.forEach((b: Button) => {
var node = b.node;
var self: any = this;
var func = self[node.name];
const node = b.node;
const self: any = this;
const func = self[node.name];
if (func) {
var event = new EventHandler();
const event = new EventHandler();
event.target = this.node;
event.handler = b.node.name;
event.component = this.name.match(regex)![1];
@@ -369,7 +369,7 @@ export class GameComponent extends Component {
protected setEvent(...args: string[]) {
const self: any = this;
for (const name of args) {
var func = self[name];
const func = self[name];
if (func)
this.on(name, func, this);
else

View File

@@ -1,11 +1,11 @@
import { Node, __private } from "cc";
import { oops } from "../../core/Oops";
import { UICallbacks } from "../../core/gui/layer/Defines";
import { ViewUtil } from "../../core/utils/ViewUtil";
import { ecs } from "../../libs/ecs/ECS";
import { CompType } from "../../libs/ecs/ECSModel";
import { CCComp } from "./CCComp";
import { CCVMParentComp } from "./CCVMParentComp";
import {Node, __private} from "cc";
import {oops} from "../../core/Oops";
import {UICallbacks} from "../../core/gui/layer/Defines";
import {ViewUtil} from "../../core/utils/ViewUtil";
import {ecs} from "../../libs/ecs/ECS";
import {CompType} from "../../libs/ecs/ECSModel";
import {CCComp} from "./CCComp";
import {CCVMParentComp} from "./CCVMParentComp";
export class ModuleUtil {
/**
@@ -20,9 +20,9 @@ export class ModuleUtil {
ctor: __private.__types_globals__Constructor<T> | __private.__types_globals__AbstractedConstructor<T>,
uiId: number,
uiArgs: any = null) {
var uic: UICallbacks = {
const uic: UICallbacks = {
onAdded: (node: Node, params: any) => {
var comp = node.getComponent(ctor) as ecs.Comp;
const comp = node.getComponent(ctor) as ecs.Comp;
ent.add(comp);
}
};
@@ -43,9 +43,9 @@ export class ModuleUtil {
uiId: number,
uiArgs: any = null): Promise<Node | null> {
return new Promise<Node | null>((resolve, reject) => {
var uic: UICallbacks = {
const uic: UICallbacks = {
onAdded: (node: Node, params: any) => {
var comp = node.getComponent(ctor) as ecs.Comp;
const comp = node.getComponent(ctor) as ecs.Comp;
ent.add(comp);
resolve(node);
},
@@ -58,19 +58,19 @@ export class ModuleUtil {
}
/**
* 通过资源内存中获取预制上的组件添加到ECS实体中
* @param ent 模块实体
* @param ctor 界面逻辑组件
* @param parent 显示对象父级
* @param url 显示资源地址
*/
* 通过资源内存中获取预制上的组件添加到ECS实体中
* @param ent 模块实体
* @param ctor 界面逻辑组件
* @param parent 显示对象父级
* @param url 显示资源地址
*/
public static addView<T extends CCVMParentComp | CCComp>(
ent: ecs.Entity,
ctor: __private.__types_globals__Constructor<T> | __private.__types_globals__AbstractedConstructor<T>,
parent: Node,
url: string) {
var node = ViewUtil.createPrefabNode(url);
var comp = node.getComponent(ctor)!;
const node = ViewUtil.createPrefabNode(url);
const comp = node.getComponent(ctor)!;
ent.add(comp);
node.parent = parent;
}

View File

@@ -12,7 +12,7 @@ const keys = (Object.keys(buildTimeConstants) as (keyof typeof buildTimeConstant
export class BuildTimeConstants {
constructor() {
const keyNameMaxLen = keys.reduce((len, key) => Math.max(len, key.length), 0);
var enviroment = `${keys.map((key) => {
const enviroment = `${keys.map((key) => {
const value = buildTimeConstants[key];
const valueRep = typeof value === 'boolean' ? (value ? 'true' : 'false') : value;
return `\n${key.padStart(keyNameMaxLen, ' ')} : ${valueRep}`;

View File

@@ -11,11 +11,11 @@ import { GameQueryConfig } from "./GameQueryConfig";
/** 游戏配置静态访问类 */
export class Config {
/** 环境常量 */
// public btc!: BuildTimeConstants;
// btc!: BuildTimeConstants;
/** 游戏配置数据,版本号、支持语种等数据 */
public game!: GameConfig;
game!: GameConfig;
/** 浏览器查询参数 */
public query!: GameQueryConfig;
query!: GameQueryConfig;
}

View File

@@ -77,9 +77,9 @@ export class GameConfig {
return this._data.config.loadingTimeoutGui || 1000;
}
private _data: any = null;
private readonly _data: any = null;
/** 游戏配置数据 */
public get data(): any {
get data(): any {
return this._data;
}

View File

@@ -15,23 +15,23 @@ import { StringUtil } from "../../core/utils/StringUtil";
*/
export class GameQueryConfig {
/** 调试模式开关 */
public get debug(): string {
get debug(): string {
return this._data["debug"];
}
/** 玩家帐号名 */
public get username(): string {
get username(): string {
return this._data["username"];
}
/** 语言 */
public get lang(): string {
get lang(): string {
return this._data["lang"] || "zh";
}
private _data: any = null;
/** 浏览器地址栏原始参数 */
public get data(): any {
get data(): any {
return this._data;
}