pixijs / open-games

243 stars 40 forks source link

Tracking loading progress of an assets #26

Open AlphaGamingArcade opened 5 months ago

AlphaGamingArcade commented 5 months ago

What's the best way to track the total loaded assets percentage using PIXI JS. What I did is like this

/** Load assets bundles that have nott been loaded yet */
export async function loadBundles(bundles: string | string[], onProgress?: ProgressCallback ) {
    if (typeof bundles === 'string') bundles = [bundles];

    // Check bundles requested if they exists
    for (const bundle of bundles) {
        if (!checkBundleExists(bundle)) {
            throw new Error(`[Assets] Invalid bundle: ${bundle}`);
        }
    }

    // Filter out bundles already loaded
    const loadList = bundles.filter((bundle) => !loadedBundles.includes(bundle));

    // Skip if there is no bundle left to be loaded
    if (!loadList.length) return;

    // Load bundles
    console.log('[Assets] Load:', loadList.join(', '));
    await Assets.loadBundle(loadList, onProgress);

    // Append loaded bundles to the loaded list
    loadedBundles.push(...loadList);
}
/** Initialise and start background loading of all assets */
export async function initAssets(onProgress: ProgressCallback) {
    // Load assets manifest
    assetsManifest = await fetchAssetsManifest('assets/assets-manifest.json');

    // Init PixiJS assets with this asset manifest
    await Assets.init({ manifest: assetsManifest, basePath: 'assets' });

    // Load assets for the load screen
    await loadBundles('preload', onProgress);

    // List all existing bundles names
    const allBundles = assetsManifest.bundles.map((item) => item.name);

    // Start up background loading of all bundles
    Assets.backgroundLoadBundle(allBundles);
}
    // Setup assets bundles (see assets.ts) and start up loading everything in background
    await initAssets((progress) => {
        console.log(progress)
    });

Do you happen to have any suggestion how to do it, or this is okay. Thanks