loading-assets

loading-assets

熱門

在 Phaser 4 中載入資源時使用此技能。涵蓋 Loader 外掛程式、載入圖片、Sprite Sheet、Atlas、音訊、JSON、Tilemap、點陣圖字型以及追蹤載入進度。觸發條件:preload、this.load、asset loading、spritesheet、atlas、load progress。

4萬星標
7161分支
更新於 2026/8/21
SKILL.md
唯讀
名稱
loading-assets
描述

在 Phaser 4 中載入資源時使用此技能。涵蓋 Loader 外掛程式、載入圖片、Sprite Sheet、Atlas、音訊、JSON、Tilemap、點陣圖字型以及追蹤載入進度。觸發條件:preload、this.load、asset loading、spritesheet、atlas、load progress。

載入資源

Phaser 載入器 (this.load) 負責處理所有外部內容的抓取:圖片、音訊、JSON、Tilemap、Atlas、字型、指令碼等。資源會在 preload() 中進行佇列、平行載入,並放入每個 Scene 都能存取的全域快取中。

關鍵原始碼路徑: src/loader/LoaderPlugin.js、src/loader/File.js、src/loader/filetypes/、src/loader/events/
相關技能: ../game-setup-and-config/SKILL.md、../scenes/SKILL.md、../sprites-and-images/SKILL.md

快速開始

class GameScene extends Phaser.Scene {
    preload() {
        this.load.image('logo', 'assets/logo.png');
    }

    create() {
        this.add.image(400, 300, 'logo');
    }
}

在 preload() 中載入的資源可保證在 create() 執行時準備就緒。載入器會在預載階段自動啟動。

核心概念

預載模式 (The Preload Pattern)

每個 Scene 都可以定義一個 preload() 方法。當 preload() 執行完畢時,載入器會自動啟動,並在呼叫 create() 之前等待所有排隊的檔案載入完成。

preload() {
    // 將檔案放入佇列 - 它們不會立即載入
    this.load.image('sky', 'assets/sky.png');
    this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
    this.load.audio('jump', 'assets/jump.mp3');
}

create() {
    // 上述所有資源現在皆可用
    this.add.image(400, 300, 'sky');
    this.add.sprite(100, 450, 'dude');
    this.sound.play('jump');
}

在 Preload 之外進行載入

如果你在 preload() 之外呼叫 this.load 方法(例如在 create() 中或回應使用者操作時),你必須手動啟動載入器:

create() {
    this.load.image('extra', 'assets/extra.png');
    this.load.once('complete', () => {
        this.add.image(400, 300, 'extra');
    });
    this.load.start();
}

URL 解析:baseURL、path 與 prefix

檔案的最終 URL 會解析為:baseURL + path + filename。這些可以透過遊戲設定或在執行階段設定。

preload() {
    // 設定 Base URL(加在所有相對路徑的前面)
    this.load.setBaseURL('https://cdn.example.com/');

    // 設定 Path(加在 baseURL 之後、filename 之前)
    this.load.setPath('assets/images/');

    // 設定 Key 前綴(加在快取 Key 的前面,而不是 URL)
    this.load.setPrefix('LEVEL1.');

    // 載入自:https://cdn.example.com/assets/images/hero.png
    // 快取 Key 為:LEVEL1.hero
    this.load.image('hero', 'hero.png');

    // 絕對 URL 會繞過 path/baseURL
    this.load.image('cloud', 'https://other-server.com/cloud.png');
}

這些也可以在遊戲設定中指定:

const config = {
    loader: {
        baseURL: 'https://cdn.example.com/',
        path: 'assets/',
        prefix: '',
        maxParallelDownloads: 32,
        crossOrigin: 'anonymous',
        responseType: '',
        async: true,
        timeout: 0,
        maxRetries: 2,
        imageLoadType: 'XHR' // 或 'HTMLImageElement'
    }
};

全域快取

資源儲存在全域遊戲級別的快取中,而非每個 Scene 獨立。在一個 Scene 中載入的圖片在其他所有 Scene 中都可用。貼圖會放入 game.textures(貼圖管理器)。其他資料則會放入 game.cache 子快取中(例如 game.cache.json、game.cache.audio、game.cache.xml)。

載入事件

載入器會在整個載入生命週期中觸發事件。可以使用這些事件來製作進度條和載入畫面。

preload() {
    this.load.on('progress', (value) => {
        // value 範圍為 0 到 1
        console.log(`Loading: ${Math.round(value * 100)}%`);
    });

    this.load.on('complete', () => {
        console.log('All assets loaded');
    });

    this.load.on('loaderror', (file) => {
        console.warn('Failed to load:', file.key);
    });

    this.load.image('bg', 'assets/bg.png');
}

常見模式

載入圖片與 Sprite Sheet

preload() {
    // 單一圖片
    this.load.image('star', 'assets/star.png');

    // 帶有法線貼圖 (Normal Map) 的圖片(傳入 URL 陣列:[texture, normalMap])
    this.load.image('brick', ['assets/brick.png', 'assets/brick_n.png']);

    // Sprite Sheet(固定 Frame 尺寸)
    this.load.spritesheet('explosion', 'assets/explosion.png', {
        frameWidth: 64,
        frameHeight: 64,
        startFrame: 0,
        endFrame: 23,
        margin: 0,
        spacing: 0
    });

    // SVG(可選擇以指定尺寸進行光柵化/Rasterize)
    this.load.svg('logo', 'assets/logo.svg', { width: 400, height: 400 });
}

載入音訊

preload() {
    // 單一檔案
    this.load.audio('bgm', 'assets/music.mp3');

    // 多種格式以支援跨瀏覽器
    this.load.audio('bgm', ['assets/music.ogg', 'assets/music.mp3']);

    // Audio Sprite(JSON 用於定義單一音訊檔中的具名區段)
    this.load.audioSprite('sfx', 'assets/sfx.json', [
        'assets/sfx.ogg',
        'assets/sfx.mp3'
    ]);
}

載入 JSON 與 Tilemap

preload() {
    // JSON 資料(儲存在 this.cache.json)
    this.load.json('levelData', 'assets/level1.json');

    // 帶有 dataKey 的 JSON,用於擷取子物件
    this.load.json('enemies', 'assets/data.json', 'enemies');

    // Tiled Tilemap(從 Tiled 匯出的 JSON 格式)
    this.load.tilemapTiledJSON('map', 'assets/map.json');

    // CSV Tilemap
    this.load.tilemapCSV('csvmap', 'assets/level.csv');

    // Impact Tilemap
    this.load.tilemapImpact('impactmap', 'assets/level.js');
}

create() {
    const data = this.cache.json.get('levelData');
    const map = this.make.tilemap({ key: 'map' });
}

載入 Atlas

preload() {
    // JSON Atlas(例如 TexturePacker JSON Hash/Array)
    this.load.atlas('sprites', 'assets/sprites.png', 'assets/sprites.json');

    // XML Atlas(例如 Starling/Sparrow 格式)
    this.load.atlasXML('ui', 'assets/ui.png', 'assets/ui.xml');

    // Multi-atlas(分割在多個貼圖上的 Atlas)
    this.load.multiatlas('world', 'assets/world.json', 'assets/');

    // Unity 貼圖 Atlas 格式
    this.load.unityAtlas('chars', 'assets/chars.png', 'assets/chars.txt');

    // Aseprite Atlas
    this.load.aseprite('knight', 'assets/knight.png', 'assets/knight.json');
}

create() {
    this.add.sprite(400, 300, 'sprites', 'walk_01');
}

載入點陣圖字型

preload() {
    // 需要貼圖檔與 XML/JSON 字型資料檔
    this.load.bitmapFont('pixels', 'assets/font.png', 'assets/font.xml');
}

create() {
    this.add.bitmapText(100, 100, 'pixels', 'Hello World', 32);
}

載入影片

preload() {
    // 載入影片檔。第三個參數:noAudio 旗標(預設為 false)
    this.load.video('intro', 'assets/intro.mp4');

    // 載入無音訊軌道的影片
    this.load.video('bg_loop', 'assets/loop.mp4', true);
}

載入 Web Fonts

preload() {
    // 載入字型檔 (ttf, otf, woff, woff2)
    this.load.font('myFont', 'assets/myfont.ttf', 'truetype');

    // 附帶選填的 font face 描述元
    this.load.font('boldFont', 'assets/bold.woff2', 'woff2', {
        weight: 'bold',
        style: 'normal'
    });
}

載入 Pack 檔案

Pack 檔案是一個描述一次要載入多個資源的 JSON 檔案。對於組織資源清單 (Asset Manifests) 非常有用。

preload() {
    this.load.pack('pack1', 'assets/pack.json');
}

Pack 檔案格式:

{
    "section1": {
        "baseURL": "assets/",
        "files": [
            { "type": "image", "key": "bg", "url": "bg.png" },
            { "type": "atlas", "key": "chars", "textureURL": "chars.png", "atlasURL": "chars.json" }
        ]
    }
}

配合進度條進行載入

preload() {
    const progressBar = this.add.graphics();
    const progressBox = this.add.graphics();
    progressBox.fillStyle(0x222222, 0.8);
    progressBox.fillRect(240, 270, 320, 50);

    this.load.on('progress', (value) => {
        progressBar.clear();
        progressBar.fillStyle(0xffffff, 1);
        progressBar.fillRect(250, 280, 300 * value, 30);
    });

    this.load.on('complete', () => {
        progressBar.destroy();
        progressBox.destroy();
    });

    // 將你的資源排入佇列
    this.load.image('sky', 'assets/sky.png');
    // ... 更多資源
}

所有檔案類型參考

所有 this.load 方法都接受位置引數或單一設定物件。它們也接受設定物件陣列,以批次載入同類型的多個檔案。請參閱 references/REFERENCE.md 取得完整的參數表。

貼圖: image、spritesheet、atlas、atlasXML、multiatlas、unityAtlas、aseprite、svg、htmlTexture、texture(壓縮格式)
音訊/影片: audio、audioSprite、video
資料: json、xml、text、binary、html、css、glsl
字型: bitmapFont、font
Tilemaps: tilemapTiledJSON、tilemapCSV、tilemapImpact
其他: animation、pack、script、scripts、plugin、scenePlugin、sceneFile

事件

所有事件都是在 Loader 實體 (this.load) 上觸發。

事件字串 回調函數簽名 說明
'addfile' (key, type, loader, file) 檔案已新增至載入佇列
'start' (loader) 載入器已啟動,進度為零
'load' (file) 單一檔案完成載入(處理/快取之前)
'fileprogress' (file, percentComplete) 單一檔案下載進度 (0-1)。僅在瀏覽器提供 lengthComputable 時觸發
'progress' (value) 整體載入進度更新 (0-1)
'postprocess' (loader) 所有檔案皆已載入並處理,處於內部清理之前
'filecomplete' (key, type, data) 任何檔案完成載入與處理
'filecomplete-{type}-{key}' (key, type, data) 特定檔案處理完成(例如 'filecomplete-image-hero')
'loaderror' (file) 檔案載入失敗
'complete' (loader, totalComplete, totalFailed) 佇列中的所有檔案均已處理完成

事件生命週期順序

  1. 'start' - 載入器開始
  2. 'fileprogress' - 單一檔案進度(每個檔案重複,如果可用)
  3. 'load' - 每個檔案下載完成
  4. 'filecomplete-{type}-{key}' - 特定檔案處理並快取完成
  5. 'filecomplete' - 通用的單一檔案完成通知
  6. 'progress' - 整體進度更新
  7. 'postprocess' - 所有檔案完成,清理之前
  8. 'complete' - 全部完成

常見陷阱與錯誤

Key 在其類型內必須是唯一的。 載入與現有 Key 相同的第二個圖片將記錄警告並略過它。如果需要替換,請先從貼圖管理器中移除舊貼圖。

Sprite Sheet 與 Atlas 不同。 針對固定尺寸格子的 Frame(透過索引參考)請使用 spritesheet()。針對打包且帶有具名 Frame 的貼圖 Atlas 請使用 atlas()。

在 preload 外忘記呼叫 this.load.start()。 如果你在 create() 或更晚呼叫載入方法,載入器不會自動啟動。你必須手動呼叫 this.load.start()。

Path 必須以 / 結尾。 如果你呼叫 this.load.setPath(),它會自動附加斜線。如果你直接設定 this.load.path,你必須自行包含末尾斜線。

音訊格式備援。 務必提供多種音訊格式(至少包含 OGG + MP3)以支援跨瀏覽器。載入器會選擇瀏覽器支援的第一個格式。

Pack 檔案可以覆寫 baseURL/path/prefix。 Pack 檔案中的每個區段都可以設定自己的 baseURL、path 和 prefix 值。這些僅適用於該區段內的檔案,並會在處理該區段後復原。

檔案 Key 包含前綴。 如果你設定了 this.load.setPrefix('MENU.') 並載入 Key 為 'bg' 的圖片,則實際的快取 Key 會變成 'MENU.bg'。引用該資源時,你必須使用完整的 Key。

maxRetries 屬性(預設:2) 控制載入器在放棄之前重試失敗檔案的次數。這是在建立檔案時根據 this.load.maxRetries 按檔案設定的。在新增檔案後調整它對那些檔案沒有影響。

圖片載入類型。 預設情況下,圖片透過 XHR(作為 Blob)載入。在載入器設定中設定 imageLoadType: 'HTMLImageElement' 以改用 <img> 標籤載入,這有助於解決某些環境中的 CORS 問題。

本機檔案協定。 載入器預設將 file:// 和 capacitor:// 識別為本機協定(透過 localSchemes)。從本機協定載入的檔案會跳過 CORS 標頭。

跨來源 (Cross-origin)。 當從不同網域載入資源時,特別是如果這些貼圖將與 WebGL 一起使用,請在載入器設定中設定 crossOrigin: 'anonymous'(或透過 this.load.setCORS('anonymous'))。

Key 區分大小寫且按類型分開作用域。 'Player' 和 'player' 是不同的 Key。圖片 Key 'player' 和音訊 Key 'player' 可以共存而不會衝突。

重複的 Key 會被靜默忽略。 如果 'bg' 已經存在於貼圖快取中,呼叫第二個 this.load.image('bg', ...) 不會執行任何動作。要替換請先移除舊資源。

Scene 的 update() 在 preload 期間不會觸發。 資源載入時,update() 會暫停。然而,preupdate、postupdate 和 render 仍會觸發。

進度可能會減少。 如果在載入途中新增了新檔案(例如透過 filecomplete 鏈結),由於總檔案數增加,進度值可能會下降。

Scene 負載 (在 Preload 前載入)

透過在 Scene 建構函式中定義 pack,可在 preload() 執行之前載入檔案。對於載入進度條資源非常有用。

class BootScene extends Phaser.Scene {
    constructor() {
        super({
            key: 'BootScene',
            pack: {
                files: [
                    { type: 'image', key: 'bar', url: 'loaderBar.png' }
                ]
            }
        });
    }
    // 'bar' 在 preload() 中已經可用
}

在載入途中新增檔案

使用單一檔案完成事件在作用中的載入工作階段期間鏈結相依的載入。

preload() {
    this.load.json('level1', 'level1.json');
    this.load.on('filecomplete-json-level1', (key, type, data) => {
        this.load.image(data.images);
        this.load.spritesheet(data.spritesheets);
    });
}

內聯 Pack 清單 (Inline Pack Manifests)

Pack 資料可以內聯提供,而不是從 URL 提供。

preload() {
    this.load.pack('manifest', {
        section1: {
            prefix: '',
            path: 'assets/',
            defaultType: 'image',
            files: [
                { type: 'image', key: 'bg', url: 'bg.png' },
                { type: 'spritesheet', key: 'player', url: 'player.png', frameConfig: { frameWidth: 32, frameHeight: 32 } }
            ]
        }
    });
}

快取系統

載入的資源會進入所有 Scene 共用的全域快取。貼圖儲存在貼圖管理器 (this.textures) 中;其他資源類型則會放入 this.cache 下的型態化子快取中。

// 存取快取資料
const json = this.cache.json.get('levelData');
const text = this.cache.text.get('dialogue');

// 檢查是否存在
this.cache.json.exists('levelData'); // 或 .has('levelData')
this.textures.exists('hero');

// 移除資源以釋放記憶體
this.textures.remove('hero');
this.cache.audio.remove('bgm');

// 監聽跨 Scene 的貼圖新增
this.textures.on('addtexture-mapKey', (texture) => {
    // 另一個 Scene 載入了一張 'mapKey' — 現在在此處可用
});

快取子類型:this.cache.text、this.cache.json、this.cache.audio、this.cache.binary、this.cache.shader、this.cache.xml。完整 Cache API 請參閱 references/REFERENCE.md。

原始碼檔案對照表

完整原始碼檔案對照表及 Cache API 參考請參閱 references/REFERENCE.md。

主要檔案:src/loader/LoaderPlugin.js(主要 Loader)、src/loader/File.js(基礎 File 類別)、src/loader/filetypes/(所有檔案類型載入器)、src/loader/events/(事件常數)。