Skip to content

Instantly share code, notes, and snippets.

@mauriciomassaia
Created February 6, 2020 23:42
Show Gist options
  • Save mauriciomassaia/565c6b12dc84ba76d394a5f0228a8ea6 to your computer and use it in GitHub Desktop.
Save mauriciomassaia/565c6b12dc84ba76d394a5f0228a8ea6 to your computer and use it in GitHub Desktop.
Spritesheet Manager for Pixi.js
import { Loader, Spritesheet } from 'pixi.js'
const ssMap = new Map()
function parseMiddleware (resource, next) {
if (ssMap.has(resource.name)) {
const { baseTexture } = resource.texture
const item = ssMap.get(resource.name)
item.spritesheet = new Spritesheet(baseTexture, item.data)
item.spritesheet.parse(() => {
// finished parsing spritesheet
setTimeout(next, 10)
})
} else {
next()
}
}
Loader.shared.use(parseMiddleware)
/**
* Add spritesheet data and image to be loaded and parsed
*
* @param {String} key - Key for Spritesheet
* @param {Object} data - Spritesheet JSON data as Javascript Object
* @param {String} imageUrl - Spritesheet image url
*/
function addItem (key, data, imageUrl) {
Loader.shared.add(key, imageUrl)
ssMap.set(key, { spritesheet: null, data, key })
}
function getItem (key) {
return ssMap.get(key)
}
function outputAnimationList (key, num) {
// helper function to generate json properti to inject into spritesheet.json
const a = []
const addZero = (v) => {
return v < 10 ? `0${v}` : v
}
for (let i = 0; i < num; i++) a.push(key + addZero(i))
console.log(JSON.stringify({ animations: { main: a } }))
}
export default {
addItem,
getItem,
outputAnimationList
}
@mauriciomassaia
Copy link
Author

Usage:

const KEY = 'walking-marcio'

SpritesheetManager.addItem(
  KEY,
  require(`../assets/spritesheets/${KEY}.json`),
  require(`../assets/spritesheets/${KEY}.png`)
)

const ssItem = SpritesheetManager.getItem(KEY)
const anSpr = new AnimatedSprite(ssItem.spritesheet.animations.main)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment