This commit is contained in:
2024-05-01 19:13:01 +08:00
parent cf008327aa
commit 80a32d9b1b
150 changed files with 8561 additions and 5045 deletions

View File

@@ -4,9 +4,9 @@ const { ccclass, property } = _decorator
@ccclass('CommonEvent')
export default class CommonEvent {
public static Event_FrameUpdate: string = 'Event_FrameUpdate'
public static Event_ConnectTimeOut: string = 'Event_ConnectTimeOut'
public static Event_ResourceLoader: string = 'Event_ResourceLoader'
public static Event_CheckUpdate: string = 'Event_CheckUpdate'
public static Event_Scene_Switch: string = 'Event_Scene_Switch'
public static Event_FrameUpdate: string = 'Event_FrameUpdate'
public static Event_ConnectTimeOut: string = 'Event_ConnectTimeOut'
public static Event_ResourceLoader: string = 'Event_ResourceLoader'
public static Event_CheckUpdate: string = 'Event_CheckUpdate'
public static Event_Scene_Switch: string = 'Event_Scene_Switch'
}

View File

@@ -1,37 +1,36 @@
import DateUtil from '../utils/DateUtil'
import NetConfig from './NetConfig'
export default class ManifestConfig {
public static packageUrl: string = ''
public static remoteManifestUrl: string = ''
public static remoteVersionUrl: string = ''
public static version: string = '1.0.0' //更新包要更新这里
public static assets: object = {}
public static searchPaths: Array<any> = []
public static getManifestStr(key: string) {
let obj: Object = {}
obj['packageUrl'] = `${NetConfig.hotupdateUrl}/hotupdate/${key}/`
obj['remoteManifestUrl'] =
NetConfig.hotupdateUrl +
'/hotupdate/' +
key +
'/project.manifest?t=' +
DateUtil.now()
obj['remoteManifestUrl'] = `${
NetConfig.hotupdateUrl
}/hotupdate/${key}/project.manifest?t=${DateUtil.now()}`
obj['remoteVersionUrl'] =
NetConfig.hotupdateUrl +
'/hotupdate/' +
key +
'/version.manifest?t=' +
DateUtil.now()
obj['remoteVersionUrl'] = `${
NetConfig.hotupdateUrl
}/hotupdate/${key}/version.manifest?t=${DateUtil.now()}`
obj['version'] = ManifestConfig.version
obj['assets'] = {}
obj['searchPaths'] = []
return JSON.stringify(obj)
}
public static packageUrl: string = ''
public static remoteManifestUrl: string = ''
public static remoteVersionUrl: string = ''
public static version: string = '1.0.0' // 更新包要更新这里
public static assets: object = {}
public static searchPaths: Array<any> = []
public static getManifestStr(key: string) {
const obj: {
packageUrl?: string
remoteManifestUrl?: string
remoteVersionUrl?: string
version?: string
assets?: object
searchPaths?: Array<any>
} = {}
obj.packageUrl = `${NetConfig.hotupdateUrl}/hotupdate/${key}/`
obj.remoteManifestUrl = `${NetConfig.hotupdateUrl}/hotupdate/${key}/project.manifest?t=${DateUtil.now()}`
obj.remoteManifestUrl = `${
NetConfig.hotupdateUrl
}/hotupdate/${key}/project.manifest?t=${DateUtil.now()}`
obj.remoteVersionUrl = `${NetConfig.hotupdateUrl}/hotupdate/${key}/version.manifest?t=${DateUtil.now()}`
obj.remoteVersionUrl = `${
NetConfig.hotupdateUrl
}/hotupdate/${key}/version.manifest?t=${DateUtil.now()}`
obj.version = ManifestConfig.version
obj.assets = {}
obj.searchPaths = []
return JSON.stringify(obj)
}
}

View File

@@ -1,64 +1,59 @@
import { AudioClip } from 'cc'
import { GameConfig } from '../../game/config/GameConfig'
export default class MusicConfig {
public static musicKey2Path: Map<string, string> = new Map<string, string>() //资源预加载路径
public static musicKey2Path: Map<string, string> = new Map<string, string>() // 资源预加载路径
public static musicKey2Cache: Map<string, AudioClip> = new Map<
string,
AudioClip
>() //资源加载后cache路径
public static musicKey2Cache: Map<string, AudioClip> = new Map<string, AudioClip>() // 资源加载后cache路径
public static init() {
if (
typeof GameConfig.GameName === 'undefined' ||
GameConfig.GameName === null
) {
console.error('GameConfig.GameName 未配置!')
return
}
public static init() {
if (typeof GameConfig.GameName === 'undefined' || GameConfig.GameName === null) {
console.error('GameConfig.GameName 未配置!')
return
}
const musicConfig = {
background_1: 'music/background_1',
background_2: 'music/background_2',
background_3: 'music/background_3',
deadfish_1: 'music/deadfish_1',
deadfish_2: 'music/deadfish_2',
deadfish_3: 'music/deadfish_3',
deadfish_4: 'music/deadfish_4',
deadfish_5: 'music/deadfish_5',
deadfish_6: 'music/deadfish_6',
deadfish_7: 'music/deadfish_7',
deadfish_8: 'music/deadfish_8',
deadfish_9: 'music/deadfish_9',
deadfish_10: 'music/deadfish_10',
deadfish_11: 'music/deadfish_11',
deadfish_12: 'music/deadfish_12',
deadfish_13: 'music/deadfish_13',
deadfish_14: 'music/deadfish_14',
deadfish_15: 'music/deadfish_15',
deadfish_16: 'music/deadfish_16',
deadfish_17: 'music/deadfish_17',
deadfish_18: 'music/deadfish_18',
deadfish_19: 'music/deadfish_19',
deadfish_20: 'music/deadfish_20',
deadfish_21: 'music/deadfish_21',
deadfish_22: 'music/deadfish_22',
deadfish_23: 'music/deadfish_23',
deadfish_24: 'music/deadfish_24',
deadfish_25: 'music/deadfish_25',
deadfish_26: 'music/deadfish_26',
deadfish_27: 'music/deadfish_27',
deadfish_28: 'music/deadfish_28',
deadfish_29: 'music/deadfish_29',
fire: 'music/fire',
}
// 音乐要预加载的配置
for (const key in musicConfig) {
if (musicConfig.hasOwnProperty(key)) {
const path = `${GameConfig.GameName}/${musicConfig[key]}`
MusicConfig.musicKey2Path.set(key, path)
}
}
}
const musicConfig = {
background_1: 'music/background_1',
background_2: 'music/background_2',
background_3: 'music/background_3',
deadfish_1: 'music/deadfish_1',
deadfish_2: 'music/deadfish_2',
deadfish_3: 'music/deadfish_3',
deadfish_4: 'music/deadfish_4',
deadfish_5: 'music/deadfish_5',
deadfish_6: 'music/deadfish_6',
deadfish_7: 'music/deadfish_7',
deadfish_8: 'music/deadfish_8',
deadfish_9: 'music/deadfish_9',
deadfish_10: 'music/deadfish_10',
deadfish_11: 'music/deadfish_11',
deadfish_12: 'music/deadfish_12',
deadfish_13: 'music/deadfish_13',
deadfish_14: 'music/deadfish_14',
deadfish_15: 'music/deadfish_15',
deadfish_16: 'music/deadfish_16',
deadfish_17: 'music/deadfish_17',
deadfish_18: 'music/deadfish_18',
deadfish_19: 'music/deadfish_19',
deadfish_20: 'music/deadfish_20',
deadfish_21: 'music/deadfish_21',
deadfish_22: 'music/deadfish_22',
deadfish_23: 'music/deadfish_23',
deadfish_24: 'music/deadfish_24',
deadfish_25: 'music/deadfish_25',
deadfish_26: 'music/deadfish_26',
deadfish_27: 'music/deadfish_27',
deadfish_28: 'music/deadfish_28',
deadfish_29: 'music/deadfish_29',
fire: 'music/fire',
}
// 音乐要预加载的配置
for (const key in musicConfig) {
if (Object.prototype.hasOwnProperty.call(musicConfig, key)) {
const path = `${GameConfig.GameName}/${musicConfig[key]}`
MusicConfig.musicKey2Path.set(key, path)
}
}
}
}

View File

@@ -1,3 +1,3 @@
export default class NetConfig {
public static hotupdateUrl: string = 'http://localhost:33/hotupdate'
public static hotupdateUrl: string = 'http://localhost:33/hotupdate'
}

View File

@@ -1,50 +1,53 @@
import { _decorator, Component, instantiate, Label, Node, tween, Vec3 } from 'cc'
import PrefabLoader from '../utils/PrefabLoader'
import { Component, Label, Node, Vec3, _decorator, instantiate, tween } from 'cc'
import { GameConfig } from '../../game/config/GameConfig'
import PrefabLoader from '../utils/PrefabLoader'
import DialogBase from './DialogBase'
const { ccclass, property } = _decorator
@ccclass('CommonTips')
export default class CommonTips extends Component {
public static TipsZorderIndex: number = 999
@property({ type: Label })
txtContent: Label | null = null
private tips: string = ''
private static showingNameList: Array<string> = []
onLoad() {}
public static TipsZorderIndex: number = 999
@property({ type: Label })
txtContent: Label | null = null
start() {
tween(this.node)
.by(1.5, { position: new Vec3(0, 100, 0) })
.to(0.2, { /* opacity: 0*/ scale: Vec3.ZERO })
.call(() => {
this.node.destroy()
})
.start()
}
private tips: string = ''
private static showingNameList: Array<string> = []
onDestroy() {
let index: number = CommonTips.showingNameList.indexOf(this.tips)
CommonTips.showingNameList.splice(index, 1)
this.unscheduleAllCallbacks()
}
onLoad() {}
public static showMsg(msg: string, parentNode: Node = null) {
PrefabLoader.loadPrefab(
`${GameConfig.GameName}/share/uicomponent/CommonTips`,
(loadedResource) => {
parentNode = parentNode || DialogBase.GetRootCanvas()
if (CommonTips.showingNameList.indexOf(msg) === -1) {
CommonTips.showingNameList.push(msg)
}
let dialogNode = instantiate(loadedResource)
dialogNode.setPosition(0, 0)
let dialogScript: CommonTips = dialogNode.getComponent(CommonTips)
dialogScript.tips = msg
dialogScript.txtContent.string = msg
parentNode.insertChild(dialogNode, CommonTips.TipsZorderIndex)
}
)
}
start() {
tween(this.node)
.by(1.5, { position: new Vec3(0, 100, 0) })
.to(0.2, { /* opacity: 0 */ scale: Vec3.ZERO })
.call(() => {
this.node.destroy()
})
.start()
}
onDestroy() {
const index: number = CommonTips.showingNameList.indexOf(this.tips)
CommonTips.showingNameList.splice(index, 1)
this.unscheduleAllCallbacks()
}
public static showMsg(msg: string, parentNode: Node = null) {
PrefabLoader.loadPrefab(
`${GameConfig.GameName}/share/uicomponent/CommonTips`,
(loadedResource) => {
parentNode = parentNode || DialogBase.GetRootCanvas()
if (!CommonTips.showingNameList.includes(msg)) CommonTips.showingNameList.push(msg)
const dialogNode = instantiate(loadedResource)
dialogNode.setPosition(0, 0)
const dialogScript: CommonTips = dialogNode.getComponent(CommonTips)
dialogScript.tips = msg
dialogScript.txtContent.string = msg
parentNode.insertChild(dialogNode, CommonTips.TipsZorderIndex)
},
)
}
}

View File

@@ -1,30 +1,36 @@
import { _decorator, Component, instantiate, Node, Prefab, Widget } from 'cc'
import PrefabLoader from '../utils/PrefabLoader'
import { Component, Node, Prefab, Widget, _decorator, instantiate } from 'cc'
import { GameConfig } from '../../game/config/GameConfig'
import PrefabLoader from '../utils/PrefabLoader'
import DialogBase from './DialogBase'
const { ccclass, property } = _decorator
@ccclass('DarkLayer')
export default class DarkLayer extends Component {
private static prefab: Prefab
onLoad() {
this.getComponent(Widget).target = DialogBase.GetRootCanvas()
}
start() {}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
`${GameConfig.GameName}/share/uicomponent/DarkLayer`,
(loadedResource) => {
DarkLayer.prefab = loadedResource
resolve()
}
)
})
}
public static getDarkLayer() {
let dialogNode: Node = instantiate(DarkLayer.prefab)
return dialogNode
}
private static prefab: Prefab
onLoad() {
this.getComponent(Widget).target = DialogBase.GetRootCanvas()
}
start() {}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
`${GameConfig.GameName}/share/uicomponent/DarkLayer`,
(loadedResource) => {
DarkLayer.prefab = loadedResource
resolve()
},
)
})
}
public static getDarkLayer() {
const dialogNode: Node = instantiate(DarkLayer.prefab)
return dialogNode
}
}

View File

@@ -1,65 +1,65 @@
import { _decorator, Component, Node, Widget } from 'cc'
import DarkLayer from './DarkLayer'
import { Component, Node, Widget, _decorator } from 'cc'
import { UIRoot } from '../../game/utils/UIRoot'
import DarkLayer from './DarkLayer'
const { ccclass } = _decorator
@ccclass('DialogBase')
export default class DialogBase extends Component {
private static LocalZOrder: number = 5
private darkLayer: Node | null = null
private static LocalZOrder: number = 5
private darkLayer: Node | null = null
//private static _canvas: Node;
public static GetRootCanvas(): Node {
//if(DialogBase._canvas == null)
// DialogBase._canvas = director.getScene().getChildByName('Canvas');
//return DialogBase._canvas;
return UIRoot.Instance.node
}
onLoad() {
DialogBase.LocalZOrder += 1
let closeLayer: Node = this.node.getChildByName('closeLayer')
if (closeLayer) {
let closeLayerWidget: Widget = closeLayer.getComponent(Widget)
if (closeLayerWidget) {
closeLayerWidget.target = DialogBase.GetRootCanvas()
closeLayerWidget.left = 0
closeLayerWidget.right = 0
closeLayerWidget.top = 0
closeLayerWidget.bottom = 0
}
}
this.onLoadMe()
}
// private static _canvas: Node;
public static GetRootCanvas(): Node {
// if(DialogBase._canvas == null)
// DialogBase._canvas = director.getScene().getChildByName('Canvas');
// return DialogBase._canvas;
return UIRoot.Instance.node
}
onLoadMe() {}
onLoad() {
DialogBase.LocalZOrder += 1
const closeLayer: Node = this.node.getChildByName('closeLayer')
if (closeLayer) {
const closeLayerWidget: Widget = closeLayer.getComponent(Widget)
if (closeLayerWidget) {
closeLayerWidget.target = DialogBase.GetRootCanvas()
closeLayerWidget.left = 0
closeLayerWidget.right = 0
closeLayerWidget.top = 0
closeLayerWidget.bottom = 0
}
}
this.onLoadMe()
}
start(isPlayMv: boolean = false) {
this.darkLayer = DarkLayer.getDarkLayer()
this.node.insertChild(this.darkLayer, 0) //this.node.addChild(this.darkLayer, -1);
if (isPlayMv) {
this.node.setScale(0, 0)
} else {
this.onStartMe()
}
}
onLoadMe() {}
onStartMe() {}
start(isPlayMv: boolean = false) {
this.darkLayer = DarkLayer.getDarkLayer()
this.node.insertChild(this.darkLayer, 0) // this.node.addChild(this.darkLayer, -1);
if (isPlayMv) this.node.setScale(0, 0)
else this.onStartMe()
}
onClickClose() {
this.node.destroy()
}
onStartMe() {}
update(dt) {
this.onUpdateMe(dt)
}
onClickClose() {
this.node.destroy()
}
onUpdateMe(dt) {}
update(dt) {
this.onUpdateMe(dt)
}
onDestroy() {
DialogBase.LocalZOrder -= 1
this.onDestroyMe()
}
onUpdateMe(dt) {}
onDestroyMe() {}
onDestroy() {
DialogBase.LocalZOrder -= 1
this.onDestroyMe()
}
onDestroyMe() {}
}

View File

@@ -1,78 +1,76 @@
import { _decorator, Component, instantiate, Node, Prefab, Quat, Vec3 } from 'cc'
import PrefabLoader from '../utils/PrefabLoader'
import { Component, Node, Prefab, Quat, Vec3, _decorator, instantiate } from 'cc'
import { GameConfig } from '../../game/config/GameConfig'
import PrefabLoader from '../utils/PrefabLoader'
import DialogBase from './DialogBase'
const { ccclass, property } = _decorator
@ccclass('LoadingPrefab')
export default class LoadingPrefab extends Component {
public static instance: Node
private static prefab: Prefab
public static LoadingZorderIndex: number = 99
@property({ type: Node })
loadingSp: Node | null = null
public static instance: Node
private static prefab: Prefab
public static LoadingZorderIndex: number = 99
@property({ type: Node })
loadingSp: Node | null = null
private _quatCache: Quat
private _vec3Cache: Vec3
onLoad() {
this._quatCache = new Quat()
this._vec3Cache = new Vec3()
}
private _quatCache: Quat
private _vec3Cache: Vec3
start() {}
onLoad() {
this._quatCache = new Quat()
this._vec3Cache = new Vec3()
}
public static close() {
if (!LoadingPrefab.instance) {
return
}
LoadingPrefab.instance.removeFromParent()
LoadingPrefab.instance.destroy()
LoadingPrefab.instance = null
}
start() {}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
GameConfig.GameName + '/' + 'share/uicomponent/LoadingPrefab',
(loadedResource) => {
LoadingPrefab.prefab = loadedResource
resolve()
}
)
})
}
public static close() {
if (!LoadingPrefab.instance) return
private static createLoadingPrefab(parentNode: Node = null) {
let dialogNode: Node = instantiate(LoadingPrefab.prefab)
LoadingPrefab.instance = dialogNode
if (!parentNode) {
parentNode = DialogBase.GetRootCanvas()
}
parentNode.insertChild(dialogNode, LoadingPrefab.LoadingZorderIndex)
dialogNode.setPosition(0, 0)
}
LoadingPrefab.instance.removeFromParent()
LoadingPrefab.instance.destroy()
LoadingPrefab.instance = null
}
public static async show(parentNode: Node = null) {
if (LoadingPrefab.instance) return
if (!LoadingPrefab.prefab) {
await LoadingPrefab.preLoad()
}
this.createLoadingPrefab(parentNode)
}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
`${GameConfig.GameName}/share/uicomponent/LoadingPrefab`,
(loadedResource) => {
LoadingPrefab.prefab = loadedResource
resolve()
},
)
})
}
update(dt) {
this.loadingSp.getRotation(this._quatCache)
Quat.toEuler(this._vec3Cache, this._quatCache)
this._vec3Cache.z += 10
this.loadingSp.setRotationFromEuler(this._vec3Cache)
if (this._vec3Cache.z >= 360) {
this.loadingSp.getRotation(Quat.IDENTITY)
}
}
private static createLoadingPrefab(parentNode: Node = null) {
const dialogNode: Node = instantiate(LoadingPrefab.prefab)
LoadingPrefab.instance = dialogNode
if (!parentNode) parentNode = DialogBase.GetRootCanvas()
public static clear() {
LoadingPrefab.instance = null
LoadingPrefab.prefab = null
}
parentNode.insertChild(dialogNode, LoadingPrefab.LoadingZorderIndex)
dialogNode.setPosition(0, 0)
}
public static async show(parentNode: Node = null) {
if (LoadingPrefab.instance) return
if (!LoadingPrefab.prefab) await LoadingPrefab.preLoad()
this.createLoadingPrefab(parentNode)
}
update(dt) {
this.loadingSp.getRotation(this._quatCache)
Quat.toEuler(this._vec3Cache, this._quatCache)
this._vec3Cache.z += 10
this.loadingSp.setRotationFromEuler(this._vec3Cache)
if (this._vec3Cache.z >= 360) this.loadingSp.getRotation(Quat.IDENTITY)
}
public static clear() {
LoadingPrefab.instance = null
LoadingPrefab.prefab = null
}
}

View File

@@ -1,90 +1,76 @@
import { _decorator, Component, instantiate, Node, Prefab } from 'cc'
import PrefabLoader from '../utils/PrefabLoader'
import Progress from './Progress'
import { Component, Node, Prefab, _decorator, instantiate } from 'cc'
import { GameConfig } from '../../game/config/GameConfig'
import PrefabLoader from '../utils/PrefabLoader'
import DialogBase from './DialogBase'
import Progress from './Progress'
const { ccclass, property } = _decorator
@ccclass('LoadingScenePrefab')
export default class LoadingScenePrefab extends Component {
public static instance: Node
private static prefab: Prefab
public static LoadingZorderIndex: number = 99
@property({ type: Node })
private progressNode: Node | null = null
onLoad() {}
public static instance: Node
private static prefab: Prefab
public static LoadingZorderIndex: number = 99
@property({ type: Node })
private progressNode: Node | null = null
start() {}
onLoad() {}
public updateProgress(
completedCount: number,
totalCount: number,
item: any = null
) {
this.progressNode
.getComponent(Progress)
.updateProgress(
completedCount,
totalCount,
'消耗流量,预下载所有"鱼"类中,请耐心等待...'
)
}
start() {}
public static updateLoading(
completedCount: number,
totalCount: number,
item: any = null
) {
if (LoadingScenePrefab.instance) {
let nodeTs: LoadingScenePrefab =
LoadingScenePrefab.instance.getComponent(LoadingScenePrefab)
if (nodeTs) {
nodeTs.updateProgress(completedCount, totalCount, item)
}
}
}
public updateProgress(completedCount: number, totalCount: number, item: any = null) {
this.progressNode
.getComponent(Progress)
.updateProgress(completedCount, totalCount, '消耗流量,预下载所有"鱼"类中,请耐心等待...')
}
private static createPrefab(parentNode: Node = null) {
let dialogNode: Node = instantiate(LoadingScenePrefab.prefab)
LoadingScenePrefab.instance = dialogNode
if (!parentNode) {
parentNode = DialogBase.GetRootCanvas()
}
parentNode.insertChild(dialogNode, LoadingScenePrefab.LoadingZorderIndex)
dialogNode.setPosition(0, 0)
}
public static updateLoading(completedCount: number, totalCount: number, item: any = null) {
if (LoadingScenePrefab.instance) {
const nodeTs: LoadingScenePrefab =
LoadingScenePrefab.instance.getComponent(LoadingScenePrefab)
if (nodeTs) nodeTs.updateProgress(completedCount, totalCount, item)
}
}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
GameConfig.GameName + '/' + 'share/uicomponent/LoadingScenePrefab',
(loadedResource: Prefab) => {
LoadingScenePrefab.prefab = loadedResource
resolve()
}
)
})
}
private static createPrefab(parentNode: Node = null) {
const dialogNode: Node = instantiate(LoadingScenePrefab.prefab)
LoadingScenePrefab.instance = dialogNode
if (!parentNode) parentNode = DialogBase.GetRootCanvas()
public static close() {
if (!LoadingScenePrefab.instance) {
return
}
LoadingScenePrefab.instance.destroy()
LoadingScenePrefab.instance = null
}
parentNode.insertChild(dialogNode, LoadingScenePrefab.LoadingZorderIndex)
dialogNode.setPosition(0, 0)
}
public static async show(parentNode: Node = null) {
if (LoadingScenePrefab.instance) return
if (!LoadingScenePrefab.prefab) {
await LoadingScenePrefab.preLoad()
}
this.createPrefab(parentNode)
}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
`${GameConfig.GameName}/share/uicomponent/LoadingScenePrefab`,
(loadedResource: Prefab) => {
LoadingScenePrefab.prefab = loadedResource
resolve()
},
)
})
}
public static clear() {
LoadingScenePrefab.instance = null
LoadingScenePrefab.prefab = null
}
public static close() {
if (!LoadingScenePrefab.instance) return
LoadingScenePrefab.instance.destroy()
LoadingScenePrefab.instance = null
}
public static async show(parentNode: Node = null) {
if (LoadingScenePrefab.instance) return
if (!LoadingScenePrefab.prefab) await LoadingScenePrefab.preLoad()
this.createPrefab(parentNode)
}
public static clear() {
LoadingScenePrefab.instance = null
LoadingScenePrefab.prefab = null
}
}

View File

@@ -1,9 +1,18 @@
import { _decorator, AssetManager, AudioClip, AudioSource, Component, instantiate, Prefab } from 'cc'
import {
AssetManager,
AudioClip,
AudioSource,
Component,
Prefab,
_decorator,
instantiate,
} from 'cc'
import { GameConfig } from '../../game/config/GameConfig'
import MusicConfig from '../config/MusicConfig'
import LocalStorage from '../utils/LocalStorage'
import { Logger } from '../utils/Logger'
import PrefabLoader from '../utils/PrefabLoader'
import LocalStorage from '../utils/LocalStorage'
import MusicConfig from '../config/MusicConfig'
import { GameConfig } from '../../game/config/GameConfig'
const { ccclass, property } = _decorator
@@ -13,71 +22,59 @@ const { ccclass, property } = _decorator
@ccclass('MusicPrefab')
export default class MusicPrefab extends Component {
private static instance: MusicPrefab
private static MUSIC_VOLUMN_KEY: string = 'musicVolumn'
public static musicVolumn: number = 1
public static play(key: string) {
let url: string = MusicConfig.musicKey2Path.get(key)
if (url) {
AssetManager.instance.resources.load(
url,
AudioClip,
(error: Error, clip: AudioClip) => {
if (error) {
Logger.warn(this, 'load music error===', error.message)
} else {
if (clip) {
this.instance.node.getComponent(AudioSource).clip = clip
this.instance.node.getComponent(AudioSource).volume =
this.musicVolumn
this.instance.node.getComponent(AudioSource).play()
this.instance.node.getComponent(AudioSource).loop = true
}
}
}
)
} else {
Logger.warn(this, '播放不存在的music=', key)
}
}
private static instance: MusicPrefab
private static MUSIC_VOLUMN_KEY: string = 'musicVolumn'
public static musicVolumn: number = 1
public static changeVolumn(nowVolumn: number) {
this.musicVolumn = nowVolumn
this.instance.node.getComponent(AudioSource).volume = nowVolumn
LocalStorage.setItem(
MusicPrefab.MUSIC_VOLUMN_KEY,
this.musicVolumn.toString()
)
}
public static play(key: string) {
const url: string = MusicConfig.musicKey2Path.get(key)
if (url) {
AssetManager.instance.resources.load(url, AudioClip, (error: Error, clip: AudioClip) => {
if (error) {
Logger.warn(this, 'load music error===', error.message)
} else {
if (clip) {
this.instance.node.getComponent(AudioSource).clip = clip
this.instance.node.getComponent(AudioSource).volume = this.musicVolumn
this.instance.node.getComponent(AudioSource).play()
this.instance.node.getComponent(AudioSource).loop = true
}
}
})
} else {
Logger.warn(this, '播放不存在的music=', key)
}
}
private static preInit() {
this.musicVolumn = parseFloat(
LocalStorage.getItem(MusicPrefab.MUSIC_VOLUMN_KEY)
)
if (isNaN(this.musicVolumn)) {
this.musicVolumn = 1
}
}
public static changeVolumn(nowVolumn: number) {
this.musicVolumn = nowVolumn
this.instance.node.getComponent(AudioSource).volume = nowVolumn
LocalStorage.setItem(MusicPrefab.MUSIC_VOLUMN_KEY, this.musicVolumn.toString())
}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
GameConfig.GameName + '/' + 'share/uicomponent/MusicPrefab',
(loadedResource: Prefab) => {
MusicPrefab.instance =
instantiate(loadedResource).getComponent(MusicPrefab)
this.preInit()
resolve()
}
)
})
}
private static preInit() {
this.musicVolumn = Number.parseFloat(LocalStorage.getItem(MusicPrefab.MUSIC_VOLUMN_KEY))
if (Number.isNaN(this.musicVolumn)) this.musicVolumn = 1
}
public static destory() {
if (MusicPrefab.instance) {
MusicPrefab.instance.getComponent(AudioSource).stop()
MusicPrefab.instance.destroy()
}
MusicPrefab.instance = null
}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
`${GameConfig.GameName}/share/uicomponent/MusicPrefab`,
(loadedResource: Prefab) => {
MusicPrefab.instance = instantiate(loadedResource).getComponent(MusicPrefab)
this.preInit()
resolve()
},
)
})
}
public static destory() {
if (MusicPrefab.instance) {
MusicPrefab.instance.getComponent(AudioSource).stop()
MusicPrefab.instance.destroy()
}
MusicPrefab.instance = null
}
}

View File

@@ -1,56 +1,55 @@
import { _decorator, Component, Label, ProgressBar } from 'cc'
import { Component, Label, ProgressBar, _decorator } from 'cc'
const { ccclass, property } = _decorator
@ccclass('Progress')
export default class Progress extends Component {
@property(Label)
public percentLable: Label
@property(Label)
public percentLable: Label
@property(ProgressBar)
public bar: ProgressBar
@property(ProgressBar)
public bar: ProgressBar
onLoad() {
this.bar.node.active = false
this.bar.progress = 0
}
onLoad() {
this.bar.node.active = false
this.bar.progress = 0
}
start() {}
start() {}
updatePercent(current, filePercent) {
//this.percentLable.string = filePercent.toFixed(2);
}
updatePercent(current, filePercent) {
// this.percentLable.string = filePercent.toFixed(2);
}
updatefileTotal(current, filePercent) {
if (!this.bar.node.active) this.bar.node.active = true
var nowPercent = Math.round((current / filePercent) * 100)
var curMB = this.getMB(current)
var totalMB = this.getMB(filePercent)
// this.percentLable.string = "正在更新 " + nowPercent + "%" + " ( " + curMB + " / "+totalMB +" MB)";
nowPercent = Math.min(nowPercent, 100)
this.percentLable.string = '正在更新 ' + nowPercent + '%'
var percent = current / filePercent
this.bar.progress = percent
}
updatefileTotal(current: number, filePercent: number) {
if (!this.bar.node.active) this.bar.node.active = true
let nowPercent = Math.round((current / filePercent) * 100)
const curMB = this.getMB(current)
const totalMB = this.getMB(filePercent)
// this.percentLable.string = "正在更新 " + nowPercent + "%" + " ( " + curMB + " / "+totalMB +" MB)";
nowPercent = Math.min(nowPercent, 100)
this.percentLable.string = `正在更新 ${nowPercent}%`
this.bar.progress = current / filePercent
}
public updateProgress(
current,
total,
msg: string = '正在加载资源,此过程不消耗流量...'
) {
this.bar.node.active = true
// this.setMsg(msg+ current + "/" + total);
this.setMsg(msg)
this.bar.progress = current / total
}
public updateProgress(
current: number,
total: number,
msg: string = '正在加载资源,此过程不消耗流量...',
) {
this.bar.node.active = true
// this.setMsg(msg+ current + "/" + total);
this.setMsg(msg)
this.bar.progress = current / total
}
getMB(bytes) {
bytes /= 1024
bytes /= 1024
return bytes.toFixed(2)
}
getMB(bytes: number) {
bytes /= 1024
bytes /= 1024
return bytes.toFixed(2)
}
public setMsg(msg: string = '游戏加载中,请稍后...') {
this.percentLable.string = msg
}
public setMsg(msg: string = '游戏加载中,请稍后...') {
this.percentLable.string = msg
}
}

View File

@@ -1,11 +1,22 @@
import { _decorator, AssetManager, AudioClip, AudioSource, Component, instantiate, Node, NodePool, Prefab } from 'cc'
import { Logger } from '../utils/Logger'
import PrefabLoader from '../utils/PrefabLoader'
import LocalStorage from '../utils/LocalStorage'
import EventManager from '../utils/EventManager'
import {
AssetManager,
AudioClip,
AudioSource,
Component,
Node,
NodePool,
Prefab,
_decorator,
instantiate,
} from 'cc'
import { GameConfig } from '../../game/config/GameConfig'
import CommonEvent from '../config/CommonEvent'
import MusicConfig from '../config/MusicConfig'
import { GameConfig } from '../../game/config/GameConfig'
import EventManager from '../utils/EventManager'
import LocalStorage from '../utils/LocalStorage'
import { Logger } from '../utils/Logger'
import PrefabLoader from '../utils/PrefabLoader'
const { ccclass, property } = _decorator
@@ -16,120 +27,102 @@ const { ccclass, property } = _decorator
@ccclass('SoundPrefab')
export default class SoundPrefab extends Component {
private static prefab: Prefab | null = null
private static SOUND_VOLUMN_KEY: string = 'soundVolumn'
public static soundVolumn: number = 1
private static Pool_Init_Num: number = 30
private static pool: NodePool = new NodePool()
private static nowAudioNodeList: Array<Node> = []
private audioName: string = ''
private audioUrl: string = ''
private static getAudioNode() {
let node: Node = null
// if (this.pool.size() > 0) {
private static prefab: Prefab | null = null
private static SOUND_VOLUMN_KEY: string = 'soundVolumn'
public static soundVolumn: number = 1
private static Pool_Init_Num: number = 30
private static pool: NodePool = new NodePool()
private static nowAudioNodeList: Array<Node> = []
private audioName: string = ''
private audioUrl: string = ''
// node = this.pool.get();
// } else {
node = instantiate(this.prefab)
// }
return node
}
private static getAudioNode() {
let node: Node = null
// if (this.pool.size() > 0) {
public static play(key: string) {
let url: string = MusicConfig.musicKey2Path.get(key)
if (url) {
AssetManager.instance.resources.load(url, AudioClip, (error: Error, clip: AudioClip) => {
if (error) {
Logger.warn(this, 'load sound error===', error.message)
} else {
if (clip) {
let audioNode: Node = this.getAudioNode()
if (audioNode) {
audioNode.getComponent(AudioSource).clip = clip
audioNode.getComponent(AudioSource).volume =
SoundPrefab.soundVolumn
audioNode.getComponent(AudioSource).loop = false
audioNode.getComponent(AudioSource).currentTime = 0 //rewind();
audioNode.getComponent(AudioSource).play()
audioNode.getComponent(SoundPrefab).audioName = key
audioNode.getComponent(SoundPrefab).audioUrl = url
this.nowAudioNodeList.push(audioNode)
}
}
}
})
} else {
Logger.warn(this, '播放不存在的music=', key)
}
}
// node = this.pool.get();
// } else {
node = instantiate(this.prefab)
// }
return node
}
public static changeVolumn(nowVolumn: number) {
this.soundVolumn = nowVolumn
for (let i = 0; i < this.nowAudioNodeList.length; i++) {
let audioNode: Node = this.nowAudioNodeList[i]
let audioSource: AudioSource = audioNode.getComponent(AudioSource)
if (audioSource.playing) {
audioSource.volume = nowVolumn
}
}
LocalStorage.setItem(
SoundPrefab.SOUND_VOLUMN_KEY,
SoundPrefab.soundVolumn.toString()
)
}
public static play(key: string) {
const url: string = MusicConfig.musicKey2Path.get(key)
if (url) {
AssetManager.instance.resources.load(url, AudioClip, (error: Error, clip: AudioClip) => {
if (error) {
Logger.warn(this, 'load sound error===', error.message)
} else {
if (clip) {
const audioNode: Node = this.getAudioNode()
if (audioNode) {
audioNode.getComponent(AudioSource).clip = clip
audioNode.getComponent(AudioSource).volume = SoundPrefab.soundVolumn
audioNode.getComponent(AudioSource).loop = false
audioNode.getComponent(AudioSource).currentTime = 0 // rewind();
audioNode.getComponent(AudioSource).play()
audioNode.getComponent(SoundPrefab).audioName = key
audioNode.getComponent(SoundPrefab).audioUrl = url
this.nowAudioNodeList.push(audioNode)
}
}
}
})
} else {
Logger.warn(this, '播放不存在的music=', key)
}
}
private static preInit() {
EventManager.instance.addListener(
CommonEvent.Event_FrameUpdate,
this.updateFrame,
this
)
SoundPrefab.soundVolumn = parseFloat(
LocalStorage.getItem(SoundPrefab.SOUND_VOLUMN_KEY)
)
if (isNaN(SoundPrefab.soundVolumn)) {
SoundPrefab.soundVolumn = 1
}
}
public static changeVolumn(nowVolumn: number) {
this.soundVolumn = nowVolumn
for (let i = 0; i < this.nowAudioNodeList.length; i++) {
const audioNode: Node = this.nowAudioNodeList[i]
const audioSource: AudioSource = audioNode.getComponent(AudioSource)
if (audioSource.playing) audioSource.volume = nowVolumn
}
LocalStorage.setItem(SoundPrefab.SOUND_VOLUMN_KEY, SoundPrefab.soundVolumn.toString())
}
private static updateFrame() {
for (let i = 0; i < this.nowAudioNodeList.length; i++) {
let audioNode: Node = this.nowAudioNodeList[i]
let audioSource: AudioSource = audioNode.getComponent(AudioSource)
if (!audioSource.playing) {
SoundPrefab.nowAudioNodeList.splice(i, 1)
}
}
}
private static preInit() {
EventManager.instance.addListener(CommonEvent.Event_FrameUpdate, this.updateFrame, this)
SoundPrefab.soundVolumn = Number.parseFloat(LocalStorage.getItem(SoundPrefab.SOUND_VOLUMN_KEY))
if (Number.isNaN(SoundPrefab.soundVolumn)) SoundPrefab.soundVolumn = 1
}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
GameConfig.GameName + '/' + 'share/uicomponent/SoundPrefab',
(loadedResource: Prefab) => {
SoundPrefab.prefab = loadedResource
this.preInit()
// for (let i = 0; i < this.Pool_Init_Num; i++) {
// let tempNode: cc.Node = cc.instantiate(loadedResource);
// this.pool.put(tempNode);
// }
resolve()
}
)
})
}
private static updateFrame() {
for (let i = 0; i < this.nowAudioNodeList.length; i++) {
const audioNode: Node = this.nowAudioNodeList[i]
const audioSource: AudioSource = audioNode.getComponent(AudioSource)
if (!audioSource.playing) SoundPrefab.nowAudioNodeList.splice(i, 1)
}
}
public static destory() {
EventManager.instance.removeListener(
CommonEvent.Event_FrameUpdate,
this.updateFrame
)
for (let i = 0; i < this.nowAudioNodeList.length; i++) {
let audioNode: Node = this.nowAudioNodeList[i]
audioNode.getComponent(AudioSource).stop()
audioNode.getComponent(AudioSource).destroy()
}
this.nowAudioNodeList = []
this.pool.clear()
}
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => {
PrefabLoader.loadPrefab(
`${GameConfig.GameName}/share/uicomponent/SoundPrefab`,
(loadedResource: Prefab) => {
SoundPrefab.prefab = loadedResource
this.preInit()
// for (let i = 0; i < this.Pool_Init_Num; i++) {
// let tempNode: cc.Node = cc.instantiate(loadedResource);
// this.pool.put(tempNode);
// }
resolve()
},
)
})
}
public static destory() {
EventManager.instance.removeListener(CommonEvent.Event_FrameUpdate, this.updateFrame)
for (let i = 0; i < this.nowAudioNodeList.length; i++) {
const audioNode: Node = this.nowAudioNodeList[i]
audioNode.getComponent(AudioSource).stop()
audioNode.getComponent(AudioSource).destroy()
}
this.nowAudioNodeList = []
this.pool.clear()
}
}

View File

@@ -1,21 +1,25 @@
import { _decorator, Component, SpriteFrame } from 'cc'
import { Component, SpriteFrame, _decorator } from 'cc'
const { ccclass, property } = _decorator
@ccclass('TextureMgr')
export default class TextureMgr extends Component {
@property({ type: [SpriteFrame] })
public Spriteset: SpriteFrame[] = []
@property({ type: [SpriteFrame] })
public Spriteset1: SpriteFrame[] = []
@property({ type: [SpriteFrame] })
public Spriteset2: SpriteFrame[] = []
@property({ type: [SpriteFrame] })
public Spriteset3: SpriteFrame[] = []
@property({ type: [SpriteFrame] })
public Spriteset4: SpriteFrame[] = []
@property({ type: [SpriteFrame] })
public Spriteset: SpriteFrame[] = []
onLoad() {
// // init logic
}
@property({ type: [SpriteFrame] })
public Spriteset1: SpriteFrame[] = []
@property({ type: [SpriteFrame] })
public Spriteset2: SpriteFrame[] = []
@property({ type: [SpriteFrame] })
public Spriteset3: SpriteFrame[] = []
@property({ type: [SpriteFrame] })
public Spriteset4: SpriteFrame[] = []
onLoad() {
// init logic
}
}

View File

@@ -10,29 +10,25 @@ export default class AdapterHelper {
public static fixApdater() {
log('v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true')
return
let framesize = view.getFrameSize()
if (!this.winSizeWidth) {
this.winSizeWidth = screen.width
this.winSizeHeiht = screen.height
}
let designsize = view.getDesignResolutionSize()
let canvas: Canvas = DialogBase.GetRootCanvas().getComponent(Canvas)
let ratio: number = framesize.height / framesize.width
let designRatio: number = designsize.height / designsize.width
if (ratio > designRatio) {
//canvas.fitHeight = false;
//canvas.fitWidth = true;
error(
'v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true'
)
} else {
//canvas.fitHeight = true;
//canvas.fitWidth = false;
error(
'v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true'
)
}
// return
// const framesize = view.getFrameSize()
// if (!this.winSizeWidth) {
// this.winSizeWidth = screen.width
// this.winSizeHeiht = screen.height
// }
// const designsize = view.getDesignResolutionSize()
// const canvas: Canvas = DialogBase.GetRootCanvas().getComponent(Canvas)
// const ratio: number = framesize.height / framesize.width
// const designRatio: number = designsize.height / designsize.width
// if (ratio > designRatio) {
// canvas.fitHeight = false;
// canvas.fitWidth = true;
// error('v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true')
// } else {
// // canvas.fitHeight = true;
// // canvas.fitWidth = false;
// error('v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true')
// }
}
}

View File

@@ -4,45 +4,39 @@ const { ccclass, property } = _decorator
@ccclass('BitUtil')
export default class BitUtil {
//index是二进制从右到左
// index是二进制从右到左
public static isBitSet(value: number, index: number): boolean {
let str: string = value.toString(2)
return parseInt(str[str.length - 1 - index]) == 1
const str: string = value.toString(2)
return Number.parseInt(str[str.length - 1 - index]) === 1
}
//从右到左计算
// 从右到左计算
public static setBitValue(value: number, index: number): number {
let newValue: number = value
let str: string = value.toString(2)
const str: string = value.toString(2)
let newStr: string = ''
let maxIndex = Math.max(str.length - 1, index)
const maxIndex = Math.max(str.length - 1, index)
for (let i = 0; i <= maxIndex; i++) {
if (index == i) {
newStr = '1' + newStr
if (index === i) {
newStr = `1${newStr}`
} else {
if (str[i] == undefined) {
newStr = '0' + newStr
} else {
newStr = str[i] + newStr
}
if (str[i] === undefined) newStr = `0${newStr}`
else newStr = str[i] + newStr
}
}
newValue = parseInt(newStr, 2)
newValue = Number.parseInt(newStr, 2)
return newValue
}
public static clearBitValue(value: number, index: number) {
let newValue: number = value
let str: string = value.toString(2)
const str: string = value.toString(2)
let newStr: string = ''
for (let i = str.length - 1; i >= 0; i--) {
if (index == str.length - 1 - i) {
newStr = '0' + newStr
} else {
newStr = str[i] + newStr
}
if (index === str.length - 1 - i) newStr = `0${newStr}`
else newStr = str[i] + newStr
}
newValue = parseInt(newStr, 2)
newValue = Number.parseInt(newStr, 2)
return newValue
}
}

View File

@@ -1,11 +1,11 @@
import { _decorator, Color } from 'cc'
import { Color, _decorator } from 'cc'
const { ccclass, property } = _decorator
@ccclass('ColorHelper')
export default class ColorHelper {
public static getColor(hexStr: string): Color {
let color: Color = Color.BLACK
const color: Color = Color.BLACK
return color.fromHEX(hexStr)
}
}

View File

@@ -1,136 +1,83 @@
export default class DateUtil {
public static formatNumStr(num: number) {
let str = '' + num
if (num < 10) {
str = '0' + num
}
let str = `${num}`
if (num < 10) str = `0${num}`
return str
}
public static formateYearMonthDayStr(timestamp: number) {
let date: Date = new Date(timestamp)
return (
date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
)
const date: Date = new Date(timestamp)
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
}
public static formateMonthDayStr(timestamp: number) {
let date: Date = new Date(timestamp)
return date.getMonth() + 1 + '月' + date.getDate() + '日'
const date: Date = new Date(timestamp)
return `${date.getMonth() + 1}${date.getDate()}`
}
// timestamp:1453094034000 2018-1-31 19:53:44
//根据时间戳返回 2018-1-31 19:53:44
// 根据时间戳返回 2018-1-31 19:53:44
public static formatDateStr(timestamp: number) {
let date: Date = new Date(timestamp)
return (
date.getFullYear() +
'-' +
(date.getMonth() + 1) +
'-' +
date.getDate() +
' ' +
this.formatNumStr(date.getHours()) +
':' +
this.formatNumStr(date.getMinutes()) +
':' +
this.formatNumStr(date.getSeconds())
)
const date: Date = new Date(timestamp)
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${this.formatNumStr(
date.getHours(),
)}:${this.formatNumStr(date.getMinutes())}:${this.formatNumStr(date.getSeconds())}`
}
// timestamp:1453094034000 2018-1-31-19-53-44
//根据时间戳返回 2018-1-31-19-53-44
// 根据时间戳返回 2018-1-31-19-53-44
public static formatDateStr2(timestamp: number) {
let date: Date = new Date(timestamp)
return (
date.getFullYear() +
'-' +
(date.getMonth() + 1) +
'-' +
date.getDate() +
'-' +
this.formatNumStr(date.getHours()) +
'-' +
this.formatNumStr(date.getMinutes()) +
'-' +
this.formatNumStr(date.getSeconds())
)
const date: Date = new Date(timestamp)
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${this.formatNumStr(date.getHours())}-${this.formatNumStr(date.getMinutes())}-${this.formatNumStr(date.getSeconds())}`
}
// timestamp:1453094034000 2018-1-31
//根据时间戳返回 2018-1-31
// 根据时间戳返回 2018-1-31
public static formatDateStr3(timestamp: number) {
let date: Date = new Date(timestamp)
return (
date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
)
const date: Date = new Date(timestamp)
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
}
// timestamp:1453094034000
//根据时间戳返回 19:53
// 根据时间戳返回 19:53
public static formatHourMinStr(timestamp: number) {
let date: Date = new Date(timestamp)
return (
this.formatNumStr(date.getHours()) +
':' +
this.formatNumStr(date.getMinutes())
)
const date: Date = new Date(timestamp)
return `${this.formatNumStr(date.getHours())}:${this.formatNumStr(date.getMinutes())}`
}
// timestamp:1453094034000
//根据时间戳返回 19:53:11
// 根据时间戳返回 19:53:11
public static formatHourMinSecondStr(timestamp: number) {
let date: Date = new Date(timestamp)
return (
this.formatNumStr(date.getHours()) +
':' +
this.formatNumStr(date.getMinutes()) +
':' +
this.formatNumStr(date.getSeconds())
)
const date: Date = new Date(timestamp)
return `${this.formatNumStr(date.getHours())}:${this.formatNumStr(date.getMinutes())}:${this.formatNumStr(date.getSeconds())}`
}
public static now(): number {
let date: Date = new Date()
const date: Date = new Date()
return date.getTime()
}
public static betweenTime(startTime: number, endTime: number) {
let date: Date = new Date()
if (date.getTime() >= startTime && date.getTime() <= endTime) {
return true
}
return false
const date: Date = new Date()
return date.getTime() >= startTime && date.getTime() <= endTime
}
//根据时间戳返回 1天19:53:11
// 根据时间戳返回 1天19:53:11
public static formatLeftTime(timestamp: number) {
let result: string = ''
let day: number = Math.floor(timestamp / (1000 * 60 * 60 * 24))
let hour: number = Math.floor(timestamp / (1000 * 60 * 60)) % 24
let min: number = Math.floor(timestamp / (1000 * 60)) % 60
let second: number = Math.floor(timestamp / 1000) % 60
result =
day +
'天' +
this.formatNumStr(hour) +
':' +
this.formatNumStr(min) +
':' +
this.formatNumStr(second)
return result
const day: number = Math.floor(timestamp / (1000 * 60 * 60 * 24))
const hour: number = Math.floor(timestamp / (1000 * 60 * 60)) % 24
const min: number = Math.floor(timestamp / (1000 * 60)) % 60
const second: number = Math.floor(timestamp / 1000) % 60
return `${day}${this.formatNumStr(hour)}:${this.formatNumStr(min)}:${this.formatNumStr(second)}`
}
public static isToday(dateTime: number): boolean {
let nowDate: Date = new Date()
let checkDate: Date = new Date(dateTime)
if (
checkDate.getFullYear() == nowDate.getFullYear() &&
checkDate.getMonth() == nowDate.getMonth() &&
checkDate.getDate() == nowDate.getDate()
) {
return true
}
return false
const nowDate: Date = new Date()
const checkDate: Date = new Date(dateTime)
return (
checkDate.getFullYear() === nowDate.getFullYear() &&
checkDate.getMonth() === nowDate.getMonth() &&
checkDate.getDate() === nowDate.getDate()
)
}
}

View File

@@ -1,4 +1,5 @@
import { Button, Color, Component, Node, Slider } from 'cc'
import ColorHelper from './ColorHelper'
export class HaoEvent {
@@ -18,20 +19,17 @@ export default class EventManager {
private callbackList = {}
public constructor() {
}
public constructor() {}
//注册事件
// 注册事件
public addListener(eventName: string, callback: Function, caller: any) {
if (this.callbackList[eventName]) {
let eventList: Array<HaoEvent> = this.callbackList[eventName]
//不同元件才放入,相同元件覆蓋
const eventList: Array<HaoEvent> = this.callbackList[eventName]
// 不同元件才放入,相同元件覆蓋
let add: boolean = true
for (let i = 0; i < eventList.length; i++) {
let event: HaoEvent = eventList[i]
if (caller === event.caller) {
add = false
}
const event: HaoEvent = eventList[i]
if (caller === event.caller) add = false
}
if (add) {
eventList.push(new HaoEvent(callback, caller))
@@ -46,7 +44,7 @@ export default class EventManager {
public removeListener(eventName: string, callback: Function) {
if (this.callbackList[eventName]) {
for (let i = this.callbackList[eventName].length - 1; i >= 0; i--) {
let event: HaoEvent = this.callbackList[eventName][i]
const event: HaoEvent = this.callbackList[eventName][i]
if (event.callback == callback) {
this.callbackList[eventName].splice(i, 1)
break
@@ -56,17 +54,15 @@ export default class EventManager {
}
public dispatchEvent(eventName, parameter?: any, ...restOfName: any[]) {
let eventList: Array<HaoEvent> = this.callbackList[eventName]
const eventList: Array<HaoEvent> = this.callbackList[eventName]
if (eventList) {
for (let i = eventList.length - 1; i >= 0; i--) {
let event: HaoEvent = eventList[i]
const event: HaoEvent = eventList[i]
event.callback.call(event.caller, event, parameter, ...restOfName)
if (event.isStop) {
break
}
if (event.isStop) break
}
for (let i = eventList.length - 1; i >= 0; i--) {
let event: HaoEvent = eventList[i]
const event: HaoEvent = eventList[i]
event.isStop = false
}
}
@@ -77,12 +73,12 @@ export default class EventManager {
objectNode: Node,
scriptName: string,
eventName: string,
data: any = null
data: any = null,
) {
var btn: Button = objectNode.addComponent(Button)
var clickEventHandler = new Component.EventHandler()
clickEventHandler.target = parentNode //这个 node 节点是你的事件处理代码组件所属的节点
clickEventHandler.component = scriptName //这个是代码文件名
const btn: Button = objectNode.addComponent(Button)
const clickEventHandler = new Component.EventHandler()
clickEventHandler.target = parentNode // 这个 node 节点是你的事件处理代码组件所属的节点
clickEventHandler.component = scriptName // 这个是代码文件名
clickEventHandler.handler = eventName
clickEventHandler.customEventData = data
btn.clickEvents.push(clickEventHandler)
@@ -94,12 +90,12 @@ export default class EventManager {
}
public removeBtnEffect(objectNode: Node) {
var b = objectNode.getComponent(Button)
const b = objectNode.getComponent(Button)
b.transition = Button.Transition.NONE
}
public addBtnEffect(objectNode: Node, scale: number = 1.1) {
var b = objectNode.getComponent(Button)
const b = objectNode.getComponent(Button)
b.transition = Button.Transition.SCALE
b.zoomScale = scale
}
@@ -107,24 +103,19 @@ export default class EventManager {
public addBtnEffect_color(
objectNode: Node,
normalC: Color = ColorHelper.getColor('#FFFFFF'),
pressC: Color = ColorHelper.getColor('#C0C0C0')
pressC: Color = ColorHelper.getColor('#C0C0C0'),
) {
var b = objectNode.getComponent(Button)
const b = objectNode.getComponent(Button)
b.transition = Button.Transition.COLOR
b.normalColor = normalC
b.pressedColor = pressC
}
public addSliderEvent(
parentNode: Node,
objectNode: Node,
EventName: string,
data: any
) {
var b = objectNode.getComponent(Slider)
var clickEventHandler = new Component.EventHandler()
clickEventHandler.target = parentNode //这个 node 节点是你的事件处理代码组件所属的节点
clickEventHandler.component = parentNode.name //这个是代码文件名
public addSliderEvent(parentNode: Node, objectNode: Node, EventName: string, data: any) {
const b = objectNode.getComponent(Slider)
const clickEventHandler = new Component.EventHandler()
clickEventHandler.target = parentNode // 这个 node 节点是你的事件处理代码组件所属的节点
clickEventHandler.component = parentNode.name // 这个是代码文件名
clickEventHandler.handler = EventName
clickEventHandler.customEventData = data
b.slideEvents.push(clickEventHandler)

View File

@@ -2,13 +2,11 @@ export default class HaoEncrypt {
public static encode(str: string) {
let result: string = ''
for (let i = 0; i < str.length; i++) {
//遍历字符串
// 遍历字符串
let code: number = str.charCodeAt(i) // //逐个提取每个字符并获取Unicode编码值
if (i % 2 == 0) {
code += 2
} else {
code += 1
}
if (i % 2 === 0) code += 2
else code += 1
result += String.fromCharCode(code)
}
return result
@@ -17,13 +15,10 @@ export default class HaoEncrypt {
public static decode(str: string) {
let result: string = ''
for (let i = 0; i < str.length; i++) {
//遍历字符串
// 遍历字符串
let code: number = str.charCodeAt(i) // //逐个提取每个字符并获取Unicode编码值
if (i % 2 == 0) {
code -= 2
} else {
code -= 1
}
if (i % 2 === 0) code -= 2
else code -= 1
result += String.fromCharCode(code)
}
return result

View File

@@ -1,18 +1,19 @@
import { native, sys } from 'cc'
import { Logger } from './Logger'
import EventManager from './EventManager'
import VersionManager from './VersionManager'
import ManifestConfig from '../config/ManifestConfig'
import ResourcePreload from '../../game/utils/ResourcePreload'
import CommonTips from '../uicomponent/CommonTips'
import EventManager from './EventManager'
import { Logger } from './Logger'
import VersionManager from './VersionManager'
export default class HotUpdate {
public static Event_CheckUpdate: string = 'Event_CheckUpdate'
public static Event_On_Progress: string = 'HotUpdate_Event_On_Progress'
public static Event_On_NeedUpdate: string = 'HotUpdate_Event_On_NeedUpdate'
public static Event_Finish_Update: string = 'HotUpdate_Event_Finish'
public static Event_On_ALREADY_UP_TO_DATE: string =
'HotUpdate_Event_On_ALREADY_UP_TO_DATE'
public static Event_On_ALREADY_UP_TO_DATE: string = 'HotUpdate_Event_On_ALREADY_UP_TO_DATE'
public static Event_On_Fail_Update: string = 'HotUpdate_Event_On_Fail_Update'
private _am: any
private _checkListener: null
@@ -27,21 +28,16 @@ export default class HotUpdate {
private key: string
private hotupdateIndex: number
constructor() {
}
constructor() {}
public init(
index: number,
key: string = 'Code-remote-asset',
manifestUrl: string
) {
public init(index: number, key: string = 'Code-remote-asset', manifestUrl: string) {
if (sys.isNative) {
this.hotupdateIndex = index
this.key = key
this.manifestUrl = manifestUrl
this.storagePath = '获取this.storagePath报错了'
Logger.log(this, 'init removeDirectory=', this.storagePath + '_temp')
Logger.log(this, 'init removeDirectory=', `${this.storagePath}_temp`)
}
this.needUpdate = false
this.isUpdating = false
@@ -52,38 +48,25 @@ export default class HotUpdate {
private jumpToPack() {
let url: string
if (sys.isNative) {
if (sys.os == sys.OS.ANDROID) {
url = VersionManager.instance.apkStoreUrl
} else if (sys.os == sys.OS.IOS) {
url = VersionManager.instance.iosStoreUrl
}
if (sys.os === sys.OS.ANDROID) url = VersionManager.instance.apkStoreUrl
else if (sys.os === sys.OS.IOS) url = VersionManager.instance.iosStoreUrl
}
Logger.info(
this,
'jumpToPack==androidurl===',
VersionManager.instance.apkStoreUrl
)
Logger.info(
this,
'jumpToPack==iosStoreUrl===',
VersionManager.instance.iosStoreUrl
)
Logger.info(this, 'jumpToPack==androidurl===', VersionManager.instance.apkStoreUrl)
Logger.info(this, 'jumpToPack==iosStoreUrl===', VersionManager.instance.iosStoreUrl)
Logger.info(this, 'jumpToPack=====', url)
sys.openURL(url)
// cc.game.end();
}
//显示强制更新,即更细包面板
// 显示强制更新,即更细包面板
private showPackUpdateDialog() {
CommonTips.showMsg(
'有新的版本需要更新,下载后请先卸载,以前的版本,再安装!'
)
CommonTips.showMsg('有新的版本需要更新,下载后请先卸载,以前的版本,再安装!')
this.jumpToPack()
this.showPackUpdateDialog()
}
private checkCb(event: any) {
Logger.log(this, 'checkCb Code: =================' + event.getEventCode())
Logger.log(this, `checkCb Code: =================${event.getEventCode()}`)
switch (event.getEventCode()) {
case native.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
Logger.info(this, 'No local manifest file found, hot update skipped.')
@@ -103,18 +86,18 @@ export default class HotUpdate {
this,
'new version found, please try to update.',
this.localBigVersion,
this.remoteBigVersion
this.remoteBigVersion,
)
if (
this.key == VersionManager.Config_Key[0] &&
this.key === VersionManager.Config_Key[0] &&
this.localBigVersion < this.remoteBigVersion
) {
//更新大版本
// 更新大版本
Logger.info(
this,
'new version found, please try to update======packupdate=',
this.localBigVersion,
this.remoteBigVersion
this.remoteBigVersion,
)
this.showPackUpdateDialog()
} else {
@@ -122,14 +105,11 @@ export default class HotUpdate {
this,
'new version found, please try to update======hotupdate=',
this.localBigVersion,
this.remoteBigVersion
this.remoteBigVersion,
)
// this._am.update();
this.needUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_NeedUpdate,
this.key
)
EventManager.instance.dispatchEvent(HotUpdate.Event_On_NeedUpdate, this.key)
}
break
case native.EventAssetsManager.UPDATE_PROGRESSION:
@@ -142,14 +122,14 @@ export default class HotUpdate {
'UPDATE_PROGRESSION2222==========',
this.key,
event.getDownloadedBytes(),
event.getTotalBytes()
event.getTotalBytes(),
)
if (event.getTotalBytes() > 0) {
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_Progress,
event.getDownloadedBytes(),
event.getTotalBytes(),
this.key
this.key,
)
}
break
@@ -162,23 +142,16 @@ export default class HotUpdate {
this.failUpdate()
break
case native.EventAssetsManager.ERROR_UPDATING:
let fullFilePath: string = this.storagePath + '/' + event.getAssetId()
let tempFilePath: string =
this.storagePath + '_temp/' + event.getAssetId()
const fullFilePath: string = `${this.storagePath}/${event.getAssetId()}`
const tempFilePath: string = `${this.storagePath}_temp/${event.getAssetId()}`
Logger.warn(this, 'fullFilePath====', fullFilePath)
Logger.warn(this, 'tempFilePath====', tempFilePath)
// jsb.fileUtils.removeFile(tempFilePath);
Logger.warn(
this,
'ERROR_UPDATING=============',
event.getAssetId(),
event.getMessage()
)
Logger.warn(this, 'ERROR_UPDATING=============', event.getAssetId(), event.getMessage())
this.failUpdate()
break
default:
// this.failUpdate();
return
// this.failUpdate();
}
}
@@ -187,21 +160,20 @@ export default class HotUpdate {
Logger.log(this, 'Checking or updating ...')
return
}
let hotupdateUrlKey: string =
VersionManager.Config_Url_Key[this.hotupdateIndex]
const hotupdateUrlKey: string = VersionManager.Config_Url_Key[this.hotupdateIndex]
Logger.log(this, 'checkoutUpdate=====', this.manifestUrl, hotupdateUrlKey)
if (!this._am) {
this._am = new native.AssetsManager(
'',
this.storagePath,
this.versionCompareHandle.bind(this)
this.versionCompareHandle.bind(this),
)
}
// this._am.setMaxConcurrentTask(1);
let manifestStr: string = ManifestConfig.getManifestStr(hotupdateUrlKey)
const manifestStr: string = ManifestConfig.getManifestStr(hotupdateUrlKey)
Logger.log(this, 'checkUpdate=======manifestStr=======', manifestStr)
let manifest = new native.Manifest(manifestStr, this.storagePath)
this._am.setVerifyCallback(function(filePath, asset) {
const manifest = new native.Manifest(manifestStr, this.storagePath)
this._am.setVerifyCallback((filePath, asset) => {
return true
// var md5 = calculateMD5(filePath);
// if (md5 === asset.md5)
@@ -223,46 +195,33 @@ export default class HotUpdate {
private versionCompareHandle(versionA: string, versionB: string) {
const vA = versionA.split('.')
const vB = versionB.split('.')
Logger.log(
this,
'versionCompareHandle======',
this.key,
VersionManager.Config_Key[0]
)
if (this.key == VersionManager.Config_Key[0]) {
Logger.log(this, 'versionCompareHandle======', this.key, VersionManager.Config_Key[0])
if (this.key === VersionManager.Config_Key[0]) {
Logger.log(this, 'versionCompareHandle22===', versionA, versionB)
VersionManager.instance.nowVersion = versionA
VersionManager.instance.targetVersion = versionB
}
this.localBigVersion = parseInt(vA[0])
this.remoteBigVersion = parseInt(vB[0])
this.localBigVersion = Number.parseInt(vA[0])
this.remoteBigVersion = Number.parseInt(vB[0])
for (let i = 0; i < vA.length; ++i) {
const a = parseInt(vA[i])
const b = parseInt(vB[i] || '0')
const a = Number.parseInt(vA[i])
const b = Number.parseInt(vB[i] || '0')
if (a !== b) return a - b
}
if (vB.length > vA.length) {
return -1
} else {
return 0
}
if (vB.length > vA.length) return -1
else return 0
}
public startUpdate() {
if (this.isUpdating) return
let localManifest = this._am.getLocalManifest()
let remoteManifest = this._am.getRemoteManifest()
const localManifest = this._am.getLocalManifest()
const remoteManifest = this._am.getRemoteManifest()
Logger.log(this, 'startUpdate111===', localManifest.getVersionFileUrl())
Logger.log(this, 'startUpdate2222===', localManifest.getManifestFileUrl())
Logger.log(this, 'startUpdate3333===', remoteManifest.getVersionFileUrl())
Logger.log(this, 'startUpdate4444===', remoteManifest.getManifestFileUrl())
this.isUpdating = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_Progress,
0,
100,
this.key
)
EventManager.instance.dispatchEvent(HotUpdate.Event_On_Progress, 0, 100, this.key)
this._am.update()
}
@@ -280,42 +239,19 @@ export default class HotUpdate {
private failUpdate() {
this.disposeUpdate()
this.isCheck = false
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_Fail_Update,
this.key
)
EventManager.instance.dispatchEvent(HotUpdate.Event_On_Fail_Update, this.key)
}
private alreadyUpToDate() {
this.disposeUpdate()
this.isFinishUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
this.key
)
EventManager.instance.dispatchEvent(HotUpdate.Event_On_ALREADY_UP_TO_DATE, this.key)
}
private finishUpdate(needRestart: boolean) {
Logger.info(this, '更新完成=====', needRestart)
this.disposeUpdate()
this.isFinishUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_Finish_Update,
this.key,
needRestart
)
if (false && needRestart) {
//暂时不想修 fileUtils 这个报错
var searchPaths = '' //jsb.fileUtils.getSearchPaths();暂时注释
Logger.info(this, '更新完成====searchPaths======', searchPaths)
sys.localStorage.setItem(
'HotUpdateSearchPaths',
JSON.stringify(searchPaths)
)
//jsb.fileUtils.setSearchPaths(searchPaths);暂时注释
if (this.key == VersionManager.Config_Key[0]) {
ResourcePreload.instance.restartGame()
}
}
EventManager.instance.dispatchEvent(HotUpdate.Event_Finish_Update, this.key, needRestart)
}
}

View File

@@ -1,13 +1,14 @@
import { _decorator } from 'cc'
import { Logger } from './Logger'
const { ccclass } = _decorator
@ccclass('HttpClient')
export default class HttpClient {
public static instance: HttpClient //= new HttpClient();
public static instance: HttpClient // = new HttpClient();
//example
// example
// HttpClient.instance.request("http://localhost:8080/haohttp/test", ()=>{
// console.log("http 请求 end=============");
// }, {"nickName":"jhao", "hh":1, "id":9527});
@@ -27,12 +28,10 @@ export default class HttpClient {
let resParams = ''
let nowIndex = 1
for (const key in paramsObj) {
if (paramsObj.hasOwnProperty(key)) {
if (nowIndex == 1) {
resParams += key + '=' + paramsObj[key]
} else {
resParams += '&' + key + '=' + paramsObj[key]
}
if (Object.prototype.hasOwnProperty.call(paramsObj, key)) {
if (nowIndex === 1) resParams += `${key}=${paramsObj[key]}`
else resParams += `&${key}=${paramsObj[key]}`
nowIndex += 1
}
}
@@ -44,41 +43,29 @@ export default class HttpClient {
this.responseType = responseType
}
public setContentType() {
}
public setContentType() {}
public request(
url: string,
callback: Function,
params: any = null,
timeOut: number = 5 * 1000
) {
if (params && this.methodType == 'GET') {
public request(url: string, callback: Function, params: any = null, timeOut: number = 5 * 1000) {
if (params && this.methodType === 'GET') {
let getParams: string = this.setParams(params)
// getParams = StringUtil:encodeURI(params)
getParams = encodeURI(getParams)
url += '?' + getParams
url += `?${getParams}`
}
this.xhr = new XMLHttpRequest() // http请求 fget
//this.xhr = cc.loader.getXMLHttpRequest();
let xhr: XMLHttpRequest = this.xhr
// this.xhr = cc.loader.getXMLHttpRequest();
const xhr: XMLHttpRequest = this.xhr
xhr.responseType = this.responseType
xhr.timeout = timeOut
// xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onreadystatechange = () => {
Logger.log(
this,
'status======',
xhr.status,
xhr.readyState,
xhr.statusText
)
Logger.log(this, 'status======', xhr.status, xhr.readyState, xhr.statusText)
// if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
if (xhr.readyState == 4 && xhr.status == 200) {
let response = xhr.response
if (xhr.readyState === 4 && xhr.status === 200) {
const response = xhr.response
Logger.log(this, 'http response1============', xhr)
try {
let testJson = JSON.stringify(response)
const testJson = JSON.stringify(response)
Logger.log(this, 'http response json============', testJson)
if (callback) {
callback(true, response)
@@ -91,31 +78,21 @@ export default class HttpClient {
callback = null
}
}
} else if (xhr.readyState == 4 && xhr.status == 301) {
//域名转移
Logger.log(
this,
'http response222============',
xhr.getResponseHeader('Location')
)
} else if (xhr.readyState === 4 && xhr.status === 301) {
// 域名转移
Logger.log(this, 'http response222============', xhr.getResponseHeader('Location'))
// console.log("http response333============", xhr.getAllResponseHeaders());
if (HttpClient.instance == null) HttpClient.instance = new HttpClient()
HttpClient.instance.request(xhr.getResponseHeader('Location'), callback)
} else if (xhr.readyState == 4 && xhr.status == 404) {
} else if (xhr.readyState === 4 && xhr.status === 404) {
Logger.log(this, 'http onError============')
if (callback) {
callback(false)
callback = null
}
} else {
Logger.log(
this,
'onreadystatechange else====',
xhr.status,
xhr.readyState,
xhr.response
)
if (xhr.readyState == 4) {
Logger.log(this, 'onreadystatechange else====', xhr.status, xhr.readyState, xhr.response)
if (xhr.readyState === 4) {
Logger.log(this, 'http onError else============')
if (callback) {
callback(false)
@@ -125,13 +102,7 @@ export default class HttpClient {
}
}
xhr.onprogress = () => {
Logger.log(
this,
'http onprogress===',
xhr.status,
xhr.readyState,
xhr.response
)
Logger.log(this, 'http onprogress===', xhr.status, xhr.readyState, xhr.response)
}
xhr.onerror = () => {
Logger.log(this, 'http onError============')
@@ -155,6 +126,5 @@ export default class HttpClient {
xhr.send(params)
}
public getInfo(callback: Function = null) {
}
public getInfo(callback: Function = null) {}
}

View File

@@ -16,11 +16,10 @@ export default class LocalStorage {
}
public static getInt(key: string): number {
let tempValue: string = LocalStorage.getItem(key)
const tempValue: string = LocalStorage.getItem(key)
let result: number = 0
if (tempValue) {
result = parseInt(tempValue)
}
if (tempValue) result = Number.parseInt(tempValue)
return result
}
@@ -29,11 +28,10 @@ export default class LocalStorage {
}
public static getFloat(key: string): number {
let tempValue: string = LocalStorage.getItem(key)
const tempValue: string = LocalStorage.getItem(key)
let result: number = 0
if (tempValue) {
result = parseFloat(tempValue)
}
if (tempValue) result = Number.parseFloat(tempValue)
return result
}
@@ -42,19 +40,13 @@ export default class LocalStorage {
}
public static getBoolean(key: string): boolean {
let temp: number = LocalStorage.getInt(key)
if (temp == 1) {
return true
}
return false
const temp: number = LocalStorage.getInt(key)
return temp === 1
}
public static setBoolean(key: string, value: boolean) {
if (value) {
LocalStorage.setInt(key, 1)
} else {
LocalStorage.setInt(key, 0)
}
if (value) LocalStorage.setInt(key, 1)
else LocalStorage.setInt(key, 0)
}
public static clear() {

View File

@@ -9,130 +9,78 @@ class LOG_LEVEL_TYPES {
const Log_Level_Names: Array<string> = ['debug', 'log', 'info', 'warn', 'error']
export class Logger {
public static tag: string = '[HaoJslog]' //可以设置当前游戏的前缀
public static LEVEL: number = LOG_LEVEL_TYPES.WARN //当前Logger等级
public static tag: string = '[HaoJslog]' // 可以设置当前游戏的前缀
public static LEVEL: number = LOG_LEVEL_TYPES.WARN // 当前Logger等级
public static Log_Color_Config: Array<string> = [
'color:#890;font-size:10px;',
'color:#000;font-size:11px;',
'color:#09f;font-size:12px;',
'color:#f90;font-size:13px;',
'color:#f00;font-size:15px;'
'color:#f00;font-size:15px;',
]
private static Terminal_Log: boolean = false
public static formatNow() {
let date: Date = new Date() //后端返回的时间戳是秒
return (
date.getFullYear() +
'-' +
(date.getMonth() + 1) +
'-' +
date.getDate() +
' ' +
date.getHours() +
':' +
date.getMinutes() +
':' +
date.getSeconds() +
':' +
date.getMilliseconds()
)
const date: Date = new Date() // 后端返回的时间戳是秒
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`
}
private static getLogPreKey(nowLevel: number): string {
return '[' +
Logger.formatNow() +
'] ' +
Logger.tag +
' [' +
Log_Level_Names[nowLevel] +
'] '
return `[${Logger.formatNow()}] ${Logger.tag} [${Log_Level_Names[nowLevel]}] `
}
public static debug(...params: any) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.DEBUG) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.DEBUG)
return
}
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.DEBUG)
let fileStr: string = str + params.join(' ')
const str: string = this.getLogPreKey(LOG_LEVEL_TYPES.DEBUG)
const fileStr: string = str + params.join(' ')
// LogErrorFileUtil.debug(fileStr);
if (this.Terminal_Log) {
console.log(
'%c' + str,
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
...params
)
} else {
console.info(fileStr)
}
if (this.Terminal_Log)
console.log(`%c${str}`, this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], ...params)
else console.info(fileStr)
}
public static log(...params: any) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.LOG) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.LOG)
return
}
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.LOG)
let fileStr: string = str + params.join(' ')
const str: string = this.getLogPreKey(LOG_LEVEL_TYPES.LOG)
const fileStr: string = str + params.join(' ')
// LogErrorFileUtil.log(fileStr);
if (this.Terminal_Log) {
console.log(
'%c' + str,
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
...params
)
} else {
console.info(fileStr) //console.log(str, ...params)
}
if (this.Terminal_Log)
console.log(`%c${str}`, this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], ...params)
else console.info(fileStr) // console.log(str, ...params)
}
public static info(...params: any) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.INFO) {
return
}
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.INFO)
let fileStr: string = str + params.join(' ')
if (this.Terminal_Log) {
console.info(
'%c' + str,
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
...params
)
} else {
console.info(fileStr)
}
if (Logger.LEVEL > LOG_LEVEL_TYPES.INFO) return
const str: string = this.getLogPreKey(LOG_LEVEL_TYPES.INFO)
const fileStr: string = str + params.join(' ')
if (this.Terminal_Log)
console.info(`%c${str}`, this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], ...params)
else console.info(fileStr)
}
public static warn(...params: any) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.WARN) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.WARN)
return
}
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.WARN)
let fileStr: string = str + params.join(' ')
if (this.Terminal_Log) {
console.warn(
'%c' + str,
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
...params
)
} else {
console.warn(fileStr)
}
const str: string = this.getLogPreKey(LOG_LEVEL_TYPES.WARN)
const fileStr: string = str + params.join(' ')
if (this.Terminal_Log)
console.warn(`%c${str}`, this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], ...params)
else console.warn(fileStr)
}
public static error(...params: any) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.ERROR) {
return
}
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.ERROR)
let fileStr: string = str + params.join(' ')
if (this.Terminal_Log) {
console.error(
'%c' + str,
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
...params
)
} else {
console.error(fileStr)
}
if (Logger.LEVEL > LOG_LEVEL_TYPES.ERROR) return
const str: string = this.getLogPreKey(LOG_LEVEL_TYPES.ERROR)
const fileStr: string = str + params.join(' ')
if (this.Terminal_Log)
console.error(`%c${str}`, this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], ...params)
else console.error(fileStr)
}
}

View File

@@ -11,7 +11,7 @@ export default class MathUtils {
public static distance(x1: number, y1: number, x2: number, y2: number) {
// 设两点AX1,Y1,BX2,Y2
// 距离D=X2-X1的平方+Y2-Y1平方的和开平方
return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))
return Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
}
/**
@@ -45,7 +45,7 @@ export default class MathUtils {
* @param endP
*/
public static p2pRad(startP: Vec2, endP: Vec2) {
let rad: number = Math.atan2(endP.y - startP.y, endP.x - startP.x)
const rad: number = Math.atan2(endP.y - startP.y, endP.x - startP.x)
return rad
}
@@ -54,11 +54,8 @@ export default class MathUtils {
* @param rot
*/
public static rotation2Fish(rot: number) {
if (rot >= 0 && rot <= 180) {
rot = 180 - rot
} else {
rot = -180 - rot
}
if (rot >= 0 && rot <= 180) rot = 180 - rot
else rot = -180 - rot
return rot
}
}

View File

@@ -1,4 +1,5 @@
import { Node, Vec2, Vec3 } from 'cc'
import MathUtils from './MathUtils'
export class MoveHelper {
@@ -11,7 +12,7 @@ export class MoveHelper {
speed: number,
tx: number,
ty: number,
minSpeed: number = 0.01
minSpeed: number = 0.01,
) {
let isMoving: boolean = false
let times: number = 0
@@ -20,9 +21,9 @@ export class MoveHelper {
MoveHelper._vec2_0.y = MoveHelper._vec3.y
MoveHelper._vec2_1.x = tx
MoveHelper._vec2_1.y = ty
let rad: number = MathUtils.p2pRad(MoveHelper._vec2_0, MoveHelper._vec2_1)
let speedX: number = speed * Math.cos(rad)
let speedY: number = speed * Math.sin(rad)
const rad: number = MathUtils.p2pRad(MoveHelper._vec2_0, MoveHelper._vec2_1)
const speedX: number = speed * Math.cos(rad)
const speedY: number = speed * Math.sin(rad)
if (Math.abs(MoveHelper._vec3.x - tx) > minSpeed) {
times = Math.floor(Math.abs(speedX / minSpeed))
for (let i = 0; i < times; i++) {

View File

@@ -1,4 +1,5 @@
import { _decorator, AssetManager, Prefab } from 'cc'
import { AssetManager, Prefab, _decorator } from 'cc'
import { Logger } from './Logger'
const { ccclass, property } = _decorator
@@ -10,21 +11,17 @@ export default class PrefabLoader {
public static loadPrefab(url: string, callback: Function) {
if (this.isLoading) return
this.isLoading = true
AssetManager.instance.resources.load(
url,
Prefab,
(error: Error, loadedResource) => {
if (error) {
Logger.warn(this, '载入Prefab失败, 原因:', url, error.message)
return
}
if (!(loadedResource instanceof Prefab)) {
Logger.warn(this, '你载入的不是Prefab, 你做了什么事?')
return
}
callback(loadedResource)
this.isLoading = false
AssetManager.instance.resources.load(url, Prefab, (error: Error, loadedResource) => {
if (error) {
Logger.warn(this, '载入Prefab失败, 原因:', url, error.message)
return
}
)
if (!(loadedResource instanceof Prefab)) {
Logger.warn(this, '你载入的不是Prefab, 你做了什么事?')
return
}
callback(loadedResource)
this.isLoading = false
})
}
}

View File

@@ -1,7 +1,7 @@
import { Vec2 } from 'cc'
export default class RandomUtil {
//随机minNum到maxNum的数字 包含maxNum
// 随机minNum到maxNum的数字 包含maxNum
public static nextInt(minNum: number, maxNum: number) {
return Math.floor(Math.random() * (maxNum - minNum + 1) + minNum)
}
@@ -11,27 +11,24 @@ export default class RandomUtil {
}
public static nextSign() {
let temp = Math.random()
if (temp < 0.5) {
return 1
}
const temp = Math.random()
if (temp < 0.5) return 1
return -1
}
public static nextBoolean() {
let temp = Math.random()
return temp < 0.5;
const temp = Math.random()
return temp < 0.5
}
public static randomArr(nowArr: Array<any>, needNum: number) {
let tempArr: Array<any> = nowArr.concat()
let resultArr: Array<any> = []
const tempArr: Array<any> = nowArr.concat()
const resultArr: Array<any> = []
for (let index = 0; index < needNum; index++) {
if (tempArr.length <= 0) {
break
}
let randomIndex: number = RandomUtil.nextInt(0, tempArr.length - 1)
if (tempArr.length <= 0) break
const randomIndex: number = RandomUtil.nextInt(0, tempArr.length - 1)
resultArr.push(tempArr.splice(randomIndex, 1)[0])
}
return resultArr
@@ -42,8 +39,8 @@ export default class RandomUtil {
}
public static randomP(left: number, right: number, up: number, down: number) {
let randomX: number = RandomUtil.nextNumber(left, right)
let randomY: number = RandomUtil.nextNumber(up, down)
const randomX: number = RandomUtil.nextNumber(left, right)
const randomY: number = RandomUtil.nextNumber(up, down)
return new Vec2(randomX, randomY)
}
}

View File

@@ -1,4 +1,5 @@
import { Color, Material, Node, UIRenderer, UITransform, Vec2 } from 'cc'
import ShaderMaterialPrefab from '../../game/prefab/ShaderMaterialPrefab'
export default class ShaderHelper {
@@ -9,21 +10,15 @@ export default class ShaderHelper {
*/
public static clearAllEffect(
showNode: Node,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).default
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab).default,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0)
})
})
}
@@ -36,23 +31,18 @@ export default class ShaderHelper {
public static setGrayEffect(
showNode: Node,
grayLevel: number = 1,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).grayMaterial
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab)
.grayMaterial,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
material.setProperty('grayLevel', grayLevel)
renderComponent.setMaterial(material, 0)
})
showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
material.setProperty('grayLevel', grayLevel)
renderComponent.setMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
material.setProperty('grayLevel', grayLevel)
renderComponent.setSharedMaterial(material, 0)
})
childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
material.setProperty('grayLevel', grayLevel)
renderComponent.setSharedMaterial(material, 0)
})
})
}
@@ -61,15 +51,13 @@ export default class ShaderHelper {
*/
public static showGrayMv(showNode: Node) {
let grayValue: number = 0.5
let intervalId = setInterval(() => {
const intervalId = setInterval(() => {
grayValue += 0.01
if (grayValue >= 1) {
grayValue = 1
clearInterval(intervalId)
}
if (showNode) {
ShaderHelper.setGrayEffect(showNode, grayValue)
}
if (showNode) ShaderHelper.setGrayEffect(showNode, grayValue)
}, 1)
}
@@ -82,23 +70,17 @@ export default class ShaderHelper {
public static setOldPhotoEffect(
showNode: Node,
grayLevel: number = 1,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).oldPhoto
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab).oldPhoto,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
material.setProperty('oldLevel', grayLevel)
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
material.setProperty('oldLevel', grayLevel)
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
material.setProperty('oldLevel', grayLevel)
renderComponent.setSharedMaterial(material, 0)
})
})
}
@@ -107,15 +89,13 @@ export default class ShaderHelper {
*/
public static showOldPhotoMv(showNode: Node) {
let grayValue: number = 0
let intervalId = setInterval(() => {
const intervalId = setInterval(() => {
grayValue += 0.01
if (grayValue >= 1) {
grayValue = 1
clearInterval(intervalId)
}
if (showNode) {
ShaderHelper.setOldPhotoEffect(showNode, grayValue)
}
if (showNode) ShaderHelper.setOldPhotoEffect(showNode, grayValue)
}, 1)
}
@@ -131,27 +111,21 @@ export default class ShaderHelper {
public static setGlowInner(
showNode: Node,
materialParam: any,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).glowInner
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab).glowInner,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
material.setProperty('glowColor', materialParam.glowColor)
material.setProperty('glowColorSize', materialParam.glowColorSize)
material.setProperty('glowThreshold', materialParam.glowThreshold)
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
material.setProperty('glowColor', materialParam.glowColor)
material.setProperty('glowColorSize', materialParam.glowColorSize)
material.setProperty('glowThreshold', materialParam.glowThreshold)
renderComponent.setSharedMaterial(material, 0)
renderComponent.setMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
material.setProperty('glowColor', materialParam.glowColor)
material.setProperty('glowColorSize', materialParam.glowColorSize)
material.setProperty('glowThreshold', materialParam.glowThreshold)
renderComponent.setMaterial(material, 0)
})
})
}
@@ -164,7 +138,7 @@ export default class ShaderHelper {
this.setGlowInner(showNode, {
glowColor: color,
glowColorSize: 0.015,
glowThreshold: 0.1
glowThreshold: 0.1,
})
}
@@ -173,29 +147,27 @@ export default class ShaderHelper {
*/
public static showFlash(showNode: Node, totalFlashTimes: number = 1) {
let timeCount: number = 0
let color: Color = Color.WHITE
const color: Color = Color.WHITE
let flashTimes: number = 0
let intervalId = setInterval(() => {
const intervalId = setInterval(() => {
timeCount += 1
if (timeCount % 50 == 0) {
let tempCount: number = timeCount / 50
if (tempCount % 2 == 0) {
if (timeCount % 50 === 0) {
const tempCount: number = timeCount / 50
if (tempCount % 2 === 0) {
color.a = 100
this.setGlowInner(showNode, {
glowColor: color,
glowColorSize: 0.1,
glowThreshold: 0
glowThreshold: 0,
})
} else {
flashTimes++
this.setGlowInner(showNode, {
glowColor: color,
glowColorSize: 0,
glowThreshold: 0
glowThreshold: 0,
})
if (flashTimes > totalFlashTimes) {
clearInterval(intervalId)
}
if (flashTimes > totalFlashTimes) clearInterval(intervalId)
}
}
}, 1)
@@ -210,25 +182,19 @@ export default class ShaderHelper {
public static setMosaic(
showNode: Node,
materialParam: any,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).mosaic
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab).mosaic,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
material.setProperty('xBlockCount', materialParam.xBlockCount)
material.setProperty('yBlockCount', materialParam.yBlockCount)
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
material.setProperty('xBlockCount', materialParam.xBlockCount)
material.setProperty('yBlockCount', materialParam.yBlockCount)
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
material.setProperty('xBlockCount', materialParam.xBlockCount)
material.setProperty('yBlockCount', materialParam.yBlockCount)
renderComponent.setSharedMaterial(material, 0)
})
})
}
@@ -237,17 +203,15 @@ export default class ShaderHelper {
*/
public static showMosaicMv(showNode: Node, callback: Function = null) {
let masaicTimes: number = 500
let intervalId = setInterval(() => {
const intervalId = setInterval(() => {
masaicTimes -= 2
this.setMosaic(showNode, {
xBlockCount: masaicTimes,
yBlockCount: masaicTimes
yBlockCount: masaicTimes,
})
if (masaicTimes <= 30) {
clearInterval(intervalId)
if (callback) {
callback()
}
if (callback) callback()
}
}, 1)
}
@@ -261,27 +225,22 @@ export default class ShaderHelper {
public static setRoundCornerCrop(
showNode: Node,
roundCornerRadius: number = 0.1,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).roundCornerCrop
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab)
.roundCornerCrop,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
// material.setProperty("roundCornerRadius", roundCornerRadius);
material.setProperty('xRadius', roundCornerRadius)
material.setProperty('yRadius', roundCornerRadius)
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
// material.setProperty("roundCornerRadius", roundCornerRadius);
material.setProperty('xRadius', roundCornerRadius)
material.setProperty('yRadius', roundCornerRadius)
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
// material.setProperty("roundCornerRadius", roundCornerRadius);
material.setProperty('xRadius', roundCornerRadius)
material.setProperty('yRadius', roundCornerRadius)
renderComponent.setSharedMaterial(material, 0)
})
})
}
@@ -304,33 +263,49 @@ export default class ShaderHelper {
enableGradient: boolean = true,
cropAlpha: boolean = true,
enableFog: boolean = false,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).flashLight
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab)
.flashLight,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
// showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
// material.setProperty('lightColor', lightColor)
// material.setProperty('lightWidth', lightWidth)
// material.setProperty('lightAngle', lightAngle)
// material.setProperty('enableGradient', enableGradient ? 1 : 0)
// material.setProperty('cropAlpha', cropAlpha ? 1 : 0)
// material.setProperty('enableFog', enableFog ? 1 : 0)
// renderComponent.setSharedMaterial(material, 0)
// })
// showNode.children.forEach((childNode) => {
// childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
// material.setProperty('lightColor', lightColor)
// material.setProperty('lightWidth', lightWidth)
// material.setProperty('lightAngle', lightAngle)
// material.setProperty('enableGradient', enableGradient ? 1 : 0)
// material.setProperty('cropAlpha', cropAlpha ? 1 : 0)
// material.setProperty('enableFog', enableFog ? 1 : 0)
// renderComponent.setSharedMaterial(material, 0)
// })
// })
const setMaterialProperties = (renderer: UIRenderer) => {
try {
material.setProperty('lightColor', lightColor)
material.setProperty('lightWidth', lightWidth)
material.setProperty('lightAngle', lightAngle)
material.setProperty('enableGradient', enableGradient ? 1 : 0)
material.setProperty('cropAlpha', cropAlpha ? 1 : 0)
material.setProperty('enableFog', enableFog ? 1 : 0)
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
material.setProperty('lightColor', lightColor)
material.setProperty('lightWidth', lightWidth)
material.setProperty('lightAngle', lightAngle)
material.setProperty('enableGradient', enableGradient ? 1 : 0)
material.setProperty('cropAlpha', cropAlpha ? 1 : 0)
material.setProperty('enableFog', enableFog ? 1 : 0)
renderComponent.setSharedMaterial(material, 0)
})
renderer.setSharedMaterial(material, 0)
} catch (error) {
console.error('Error setting material properties:', error)
}
}
const renderComponents = [
...showNode.getComponents(UIRenderer),
...showNode.children.flatMap(childNode => childNode.getComponents(UIRenderer)),
]
renderComponents.forEach((renderComponent: UIRenderer) => {
setMaterialProperties(renderComponent)
})
}
@@ -340,28 +315,23 @@ export default class ShaderHelper {
* @param callback
*/
public static showFlashLightMv(showNode: Node, callback: Function = null) {
let nowClor: Color = new Color(0, 0, 0, 255)
const nowClor: Color = new Color(0, 0, 0, 255)
let colorIndex: number = 0
let lightAngle: number = 0
let intervalId = setInterval(() => {
if (colorIndex == 0) {
const intervalId = setInterval(() => {
if (colorIndex === 0) {
nowClor.r = nowClor.r + 2
if (nowClor.r >= 255) {
colorIndex += 1
}
} else if (colorIndex == 1) {
if (nowClor.r >= 255) colorIndex += 1
} else if (colorIndex === 1) {
nowClor.g = nowClor.g + 2
if (nowClor.g >= 255) {
colorIndex += 1
}
if (nowClor.g >= 255) colorIndex += 1
} else {
nowClor.b = nowClor.b + 2
if (nowClor.b >= 255) {
clearInterval(intervalId)
ShaderHelper.clearAllEffect(showNode)
if (callback) {
callback()
}
if (callback) callback()
return
}
}
@@ -372,21 +342,15 @@ export default class ShaderHelper {
public static setFlag(
showNode: Node,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).flag
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab).flag,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0)
})
})
}
@@ -397,32 +361,23 @@ export default class ShaderHelper {
*/
public static setGaussian(
showNode: Node,
material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab
).gaussian
material: Material = ShaderMaterialPrefab.instance.getComponent(ShaderMaterialPrefab).gaussian,
) {
showNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
let tran = renderComponent.node.getComponent(UITransform)
showNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
const tran = renderComponent.node.getComponent(UITransform)
material.setProperty('textureSize', new Vec2(tran.contentSize.width, tran.contentSize.height))
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode.getComponents(UIRenderer).forEach((renderComponent: UIRenderer) => {
const tran = renderComponent.node.getComponent(UITransform)
material.setProperty(
'textureSize',
new Vec2(tran.contentSize.width, tran.contentSize.height)
new Vec2(tran.contentSize.width, tran.contentSize.height),
)
renderComponent.setMaterial(material, 0)
// material.setProperty("textureSize", cc.v2(showNode.width, showNode.height));
renderComponent.setSharedMaterial(material, 0)
})
showNode.children.forEach((childNode) => {
childNode
.getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => {
let tran = renderComponent.node.getComponent(UITransform)
material.setProperty(
'textureSize',
new Vec2(tran.contentSize.width, tran.contentSize.height)
)
// material.setProperty("textureSize", cc.v2(showNode.width, showNode.height));
renderComponent.setSharedMaterial(material, 0)
})
})
}
}

View File

@@ -1,5 +1,7 @@
import { sys } from 'cc'
import ManifestConfig from '../config/ManifestConfig'
import EventManager from './EventManager'
import HotUpdate from './HotUpdate'
@@ -8,7 +10,7 @@ export default class VersionManager {
public static Config_Game_Name: Array<string> = ['游戏大厅']
//热更文件下载来后存放文件夹
// 热更文件下载来后存放文件夹
public static Config_Key: Array<string> = ['main-remote-asset']
private static Config_ManifestName: string = 'project.manifest'
@@ -18,10 +20,10 @@ export default class VersionManager {
public iosStoreUrl: string = ''
public apkStoreUrl: string = ''
public nowVersion: string = ManifestConfig.version //网页显示版本号,如果是热更会替换改值
public nowVersion: string = ManifestConfig.version // 网页显示版本号,如果是热更会替换改值
public targetVersion: string = '1.0.0'
public isOpenHotUpdate: boolean = true //是否打开热更
public isOpenHotUpdate: boolean = true // 是否打开热更
private hotUpdateList: Array<HotUpdate> = []
@@ -33,27 +35,21 @@ export default class VersionManager {
public reInitAll() {
this.releaseAll()
for (let i = 0; i < VersionManager.Config_Key.length; i++) {
this.reInit(i)
}
for (let i = 0; i < VersionManager.Config_Key.length; i++) this.reInit(i)
}
public releaseAll() {
for (let i = 0; i < VersionManager.Config_Key.length; i++) {
if (this.hotUpdateList[i]) {
this.hotUpdateList[i].disposeUpdate()
}
}
for (let i = 0; i < VersionManager.Config_Key.length; i++)
if (this.hotUpdateList[i]) this.hotUpdateList[i].disposeUpdate()
}
public reInit(index: number) {
if (!this.hotUpdateList[index]) {
this.hotUpdateList[index] = new HotUpdate()
}
if (!this.hotUpdateList[index]) this.hotUpdateList[index] = new HotUpdate()
this.hotUpdateList[index].init(
index,
VersionManager.Config_Key[index],
VersionManager.Config_ManifestName
VersionManager.Config_ManifestName,
)
if (!this.isOpenHotUpdate) {
this.hotUpdateList[index].isCheck = true
@@ -63,15 +59,15 @@ export default class VersionManager {
public checkUpdate(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
const hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (sys.isNative) {
if (keyIndex == this.noUpdateIndex) {
//在大厅热更,不用子游戏热更了
if (keyIndex === this.noUpdateIndex) {
// 在大厅热更,不用子游戏热更了
hotUpdate.isCheck = true
hotUpdate.isFinishUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
VersionManager.Config_Key[keyIndex]
VersionManager.Config_Key[keyIndex],
)
} else {
hotUpdate.checkUpdate()
@@ -81,28 +77,27 @@ export default class VersionManager {
hotUpdate.isFinishUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
VersionManager.Config_Key[keyIndex]
VersionManager.Config_Key[keyIndex],
)
}
} else {
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
VersionManager.Config_Key[keyIndex]
VersionManager.Config_Key[keyIndex],
)
}
}
public startUpdate(keyIndex: number) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
const hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
hotUpdate.startUpdate()
}
public isCheck(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex == this.noUpdateIndex) {
return true
}
const hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex === this.noUpdateIndex) return true
return hotUpdate.isCheck
}
return true
@@ -110,10 +105,9 @@ export default class VersionManager {
public needUpdate(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex == this.noUpdateIndex) {
return false
}
const hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex === this.noUpdateIndex) return false
return hotUpdate.needUpdate
}
return false
@@ -121,7 +115,7 @@ export default class VersionManager {
public isUpdating(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
const hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
return hotUpdate.isUpdating
}
return false
@@ -129,10 +123,9 @@ export default class VersionManager {
public isFinishUpdate(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex == this.noUpdateIndex) {
return true
}
const hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex === this.noUpdateIndex) return true
return hotUpdate.isFinishUpdate
}
return true