Skip to content

Instantly share code, notes, and snippets.

@rmartone
Last active August 3, 2018 19:55
Show Gist options
  • Save rmartone/9b9cdcefb1ee546fa6b685a2fd0aa9ea to your computer and use it in GitHub Desktop.
Save rmartone/9b9cdcefb1ee546fa6b685a2fd0aa9ea to your computer and use it in GitHub Desktop.
Simple example using phaser-ce texture atlas with compressed textures
import { Dictionary, ErrorCallback, parallel } from 'async';
import { AnimationParser, Cache } from 'phaser';
import { Client } from './client';
/**
* pending texture atlas 'complete' callbacks
*/
const pending: Dictionary<ErrorCallback<string>> = {};
/**
* EXAMPLE Asset
* "menuAtlas": {
* "urls": {
* "truecolor": "https://somedomain.com/somebucket/menu.png"
* },
* "atlas": "https://somedomain.com/somebucket/menu.json"
* },
*/
export interface Asset {
/**
* texture atlas url
*/
atlas: string;
/**
* texture urls keyed by type: "pvrtc", "truecolor"...
*/
urls: any;
}
export function queueAsset(key: string, asset: Asset) {
const loader = Client.phaser.load;
if (!loader.onFileComplete.has(fileComplete)) {
loader.onFileComplete.add(fileComplete);
}
if (!loader.onFileError.has(fileError)) {
loader.onFileError.add(fileError);
}
// this is where the magic happens!
const keyFrameData = `${key}:JSON`;
parallel(
[
callback => {
pending[keyFrameData] = callback;
loader.json(keyFrameData, asset.atlas);
},
callback => {
pending[key] = callback;
loader.texture(key, asset.urls);
},
],
err => {
if (!err) {
const cache = Client.phaser.cache;
const frameData = AnimationParser.JSONDataHash(Client.phaser, cache.getJSON(keyFrameData));
cache.updateFrameData(key, frameData, Phaser.Cache.IMAGE);
cache.removeJSON(keyFrameData);
}
}
);
}
function fileComplete(progress: number, key: string) {
const callback = pending[key];
if (callback) {
delete pending[key];
callback();
}
}
function fileError(key: string) {
const callback = pending[key];
if (callback) {
delete pending[key];
callback(`file error loading asset for key: "${key}"`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment