From 6dc10f549f677e566d102fd92ad0f72d8f10ca10 Mon Sep 17 00:00:00 2001 From: Benjamin Odom Date: Sat, 18 May 2024 18:29:09 -0500 Subject: [PATCH] =?UTF-8?q?Fix=20Crashes=20when=20Sprites=20for=20Pok?= =?UTF-8?q?=C3=A9mon=20are=20missing=20(#1021)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix Crashes when Sprites for Pokémon are missing Fixes an issue where a missing sprite will cause the game to crash instead of using the base sprite or the Substitute sprite. Failsafes were already in place to load these backups, this code just allows a graceful fail and a simple error message instead of a crash. * Check Against OK status --- src/field/pokemon.ts | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/src/field/pokemon.ts b/src/field/pokemon.ts index 0a5e0a6a991..e25fbe5fa71 100644 --- a/src/field/pokemon.ts +++ b/src/field/pokemon.ts @@ -329,9 +329,17 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (variantSet && variantSet[this.variant] === 1) { if (variantColorCache.hasOwnProperty(key)) return resolve(); - this.scene.cachedFetch(`./images/pokemon/variant/${useExpSprite ? 'exp/' : ''}${battleSpritePath}.json`).then(res => res.json()).then(c => { - variantColorCache[key] = c; - resolve(); + this.scene.cachedFetch(`./images/pokemon/variant/${useExpSprite ? 'exp/' : ''}${battleSpritePath}.json`). + then(res => { + // Prevent the JSON from processing if it failed to load + if (!res.ok) { + console.error(`Could not load ${res.url}!`); + return; + } + res.json() + }).then(c => { + variantColorCache[key] = c; + resolve(); }); } else resolve(); @@ -493,9 +501,31 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { this.shinySparkle = shinySparkle; } + /** + * Attempts to animate a given {@linkcode Phaser.GameObjects.Sprite} + * @see {@linkcode Phaser.GameObjects.Sprite.play} + * @param sprite {@linkcode Phaser.GameObjects.Sprite} to animate + * @param tintSprite {@linkcode Phaser.GameObjects.Sprite} placed on top of the sprite to add a color tint + * @param animConfig {@linkcode String} to pass to {@linkcode Phaser.GameObjects.Sprite.play} + * @returns true if the sprite was able to be animated + */ + tryPlaySprite(sprite: Phaser.GameObjects.Sprite, tintSprite: Phaser.GameObjects.Sprite, key: string): boolean { + // Catch errors when trying to play an animation that doesn't exist + try { + sprite.play(key); + tintSprite.play(key); + } + catch(error: unknown) { + console.error(`Couldn't play animation for '${key}'!\nIs the image for this Pokemon missing?\n`, error); + + return false; + } + + return true; + } + playAnim(): void { - this.getSprite().play(this.getBattleSpriteKey()); - this.getTintSprite().play(this.getBattleSpriteKey()); + this.tryPlaySprite(this.getSprite(), this.getTintSprite(), this.getBattleSpriteKey()); } getFieldPositionOffset(): [ number, number ] {