Phaser projects must preload media resources
- @description Indicates the resource configuration
- All resources use key values
- Advantage: You don’t have to store all static resources locally
- Although the packaged resources are also in the CDN, the bundle has too many dependencies at build time, so it is split out
- Later, it can be separated and uploaded to CDN gradually
- Local calls local, CDN existing direct references
1. Create an image configuration object
-
Local resources
Just write the content before.png, followed by require() to find the static resource
const localImages: string[] = [ 'img1'.'img2'.'img... ' ] Copy the code
-
CDN resource
Url is the key to be invoked for the resource.
// Resources stored in the CDN const cdnImages = { "bg-bottom": 'https://xx.png' } Copy the code
-
Loading strategy
1. Create a key-value object to store the image configuration.
2. Take the Images dictionary and load the resource under the service through require, and append it to the object;
3. Then spell the CDN resource configuration into the picture configuration object;
4. Export image configuration objects.
// Create the image configuration object let imagesConfig = {}; // require() to obtain resources function url(fileName: string) { return require(`./images/base/${fileName}.png`)}// Query the local resource dictionary localImages.forEach(item= >{ imagesConfig[item] = url(`${item}`)})// Merge CDN resources imagesConfig = Object.assign(imagesConfig, cdnImages) // Export image configuration objects export default imagesConfig; Copy the code
-
The complete code
// images_config.ts
const localImages: Array<string> = [
'img1'.'img2'.'img... '
];
const cdnImages = {
"bg-bottom": 'https://xx.xx.png'
}
// Create the image configuration object
let imagesConfig = {};
// require() to obtain resources
function url(fileName: string) {
return require(`./images/${fileName}.png`)}// Query the local resource dictionary
localImages.forEach(item= >{
imagesConfig[item] = url(item)
})
// Merge CDN resources
imagesConfig = Object.assign(imagesConfig, cdnImages)
// Export image configuration objects
export default imagesConfig;
Copy the code
2. Build a resource loader
// assets_loader.ts
class AssetsLoader {
// To create an instance in the base scenario, pass in the Scene
constructor(private scene: Phaser.Scene){
this.scene.load.crossOrigin = 'anonymous';
}
/ / the load resources
public load(imagesConfig = {} ){
const assetsHash = {
image: imagesConfig
}
Object.keys(assetsHash).forEach(assetsType= > {
const assets = assetsHash[assetsType]
Object.keys(assets).forEach(key= > {
this.scene.load[assetsType](key, assets[key])
});
});
// Start drawing the progress bar
this.scene.load.start()
}
}
Copy the code
Instantiate the loader in the base class
The optimal scenario is to call the Create () phase of BaseScene and hang on that node, accessible to all subclasses that inherit from the parent class.
// base_scene.ts
// Introduce the loader
import AssetsLoader from 'assets_loader.ts'
// Import image profile
import imagesConfig from 'images_config.ts'
export default class BaseScene extends Phaser.Scene {
assetsLoader: AssetsLoader
constructor(sceneName: string) {
super({ key: sceneName })
}
/ * * *@function Subclasses automatically execute the create declaration cycle. Private disallows subclasses to overwrite */
private create() {
this.assetsLoader = new AssetsLoader(this) // Pass the current scene
this.build()
}
build() {
// Perform the load operation
this.assetsLoader.load(imagesConfig)
}
}
Copy the code
3. Improve the static resource configuration information and loader
However, a real Phaser project requires not only image, but also audio, video, Sprite and other resources, so the next step is to process other types of media resources in a similar way to image.
Handling audio resources:
// audios_config.ts
const localAudios: Array<string> = ['audio1'.'audio... ']
const cdnAudios = {'cdn-audio': 'https://xx.xx.mp3'}
let audiosConfig = {}
function url(fileName) {
return require(`./sounds/${fileName}.mp3`)
}
localAudios.forEach(item= > {
audiosConfig[item] = url(item)
})
audiosConfig = Object.assign(audiosConfig, cdnAudios)
export default audiosConfig
Copy the code
Handling video Resources:
// videos_config.ts
const localVideos: string[] = ['video1'.'video... ']
const cdnVideos = {'cdn-video': 'https://xx.xx.mp4'}
let videosConfig = {}
function url(fileName: string) {
return require(`./video/${fileName}.mp4`)
}
localVideos.forEach(item= > {
videosConfig[item] = url(item)
})
videosConfig = Object.assign(videosConfig, cdnVideos)
export default videosConfig
Copy the code
Processing sprites resources:
// sprites_config.ts
function url(fileName) {
return `./sprites/+ ${fileName}`
}
/ / base Sprite
const spritesConfig = {
'localSoundAnimas': url('sound_sprite.json'), / / local
'cdnSoundAnimas': 'https://xx.xx.json' // cdn
}
export default spritesConfig
Copy the code
After all the resources have been exported as objects, the uploader loads the data.
Override the load() method
/ / load
public load(imagesConfig = {}, audiosConfig = {}, videosConfig = {}, spritesConfig = {}) {
const assetsHash = {
image: imagesConfig,
audio: audiosConfig,
video: videosConfig,
multiatlas: spritesConfig,
}
Object.keys(assetsHash).forEach(assetsType= > {
const assets = assetsHash[assetsType]
Object.keys(assets).forEach(key= > {
if (assetsType == 'video') {
this.scene.load[assetsType](key, assets[key], 'canplay'.true)}else {
this.scene.load[assetsType](key, assets[key])
}
})
})
// Start drawing the progress bar
this.scene.load.start()
}
Copy the code
Override the build() call in BaseScene to pass in the other three types of media resources
import imagesConfig from 'images_config.ts'
import audiosConfig from 'audios_config.ts'
import videosConfig from 'videos_config.ts'
import spritesConfig from 'sprites_config.ts'
build() {
// Perform the load operation
this.assetsLoader.load(imagesConfig, audiosConfig, videosConfig, spritesConfig);
}
Copy the code
The last step is to check whether the resource loaded successfully
This makes it fun to call pre-loaded resources in a business scenario.