Created
June 14, 2024 12:29
-
-
Save reececomo/725a09f95b97601c417830e79cda49b5 to your computer and use it in GitHub Desktop.
Quickly generate spritesheet animations in PixiJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { AnimatedSprite, Assets, IPointData } from 'pixi.js'; | |
| /** | |
| * A simple way to load animations. | |
| */ | |
| export class SpritesheetAnimation extends AnimatedSprite { | |
| public constructor(name: string, { | |
| autoPlay = false, | |
| autoUpdate = true, | |
| updateAnchor = false, | |
| animationSpeed = 1, | |
| loop = true, | |
| onComplete = undefined as (() => void) | undefined, | |
| onFrameChange = undefined as ((_: number) => void) | undefined, | |
| onLoop = undefined as (() => void) | undefined, | |
| position = undefined as IPointData | undefined, | |
| anchor = undefined as IPointData | undefined, | |
| scale = undefined as IPointData | undefined, | |
| } = {}) { | |
| const sheet: Spritesheet = Assets.get(name); | |
| const frames = Object.values(this.sortedObject(sheet.textures)); | |
| super(frames, autoUpdate); | |
| this.updateAnchor = updateAnchor; | |
| this.animationSpeed = animationSpeed; | |
| this.loop = loop; | |
| this.onComplete = onComplete; | |
| this.onFrameChange = onFrameChange; | |
| this.onLoop = onLoop; | |
| position && this.position.copyFrom(position); | |
| anchor && this.anchor.copyFrom(anchor); | |
| scale && this.scale.copyFrom(scale); | |
| autoPlay && this.play(); | |
| } | |
| /** Returns a sorted copy of an object. */ | |
| private sortedObject<T extends object>(obj: T): T { | |
| return Object.keys(obj).sort().reduce((copy, key) => { | |
| copy[key] = obj[key]; | |
| return copy; | |
| }, {}) as T; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment