如何通过JSONP在Phaser 3.60.0中加载资源并控制执行时机
Solution for Loading JSONP Data and Images in Phaser 3.60.0
Here's how to fetch the JSONP data, load all product images, and wait for everything to be ready before displaying content in create():
Step 1: Modify the GameScene to Handle JSONP and Image Loading
class GameScene extends Phaser.Scene { constructor() { super({ key: 'GameScene' }); this.itemsData = null; // Stores the JSONP product data } preload() { // Define the JSONP callback function (bound to this scene) window.handleItems = (items) => { this.itemsData = items; // Queue all product images for loading using their IDs as keys items.forEach(item => { this.load.image(item.id, item.image); }); // Restart the loader to process the new image requests this.load.start(); }; // Load the external JSONP script (replace with your actual JSONP URL) this.load.script('jsonpData', 'https://example.com/path/to/your/jsonp'); } create() { // Exit if data failed to load if (!this.itemsData) { console.error('JSONP data failed to load'); return; } // Display each product's image and name this.itemsData.forEach((item, index) => { // Calculate position (adjust spacing/grid layout as needed) const x = 120 + (index * 220); const y = 300; // Add product image (scale down if needed) const productImage = this.add.image(x, y, item.id); productImage.setScale(0.4); // Add product name text (centered below image) this.add.text(x, y + 140, item.name, { fontSize: '18px', fill: '#000000', fontWeight: 'bold' }).setOrigin(0.5); }); } }
Key Details Explained
- JSONP Callback: We define a global
handleItemsfunction that the external JSONP script will invoke with the product data. This function stores the data in the scene and queues all product images for loading. - Loader Restart: After adding the image requests to the loader, we call
this.load.start()to tell Phaser to process these new assets. The preload phase will wait until all images are loaded before moving tocreate(). - Image Keying: Each product's image is loaded using its unique
idas the key, making it easy to reference when displaying the image increate(). - Layout: The code arranges products in a horizontal row—adjust the
xcalculation if you want a grid or different layout.
Important Notes
- Replace
https://example.com/path/to/your/jsonpwith the actual URL of your JSONP endpoint. - Ensure the external server allows cross-origin requests (JSONP inherently bypasses CORS, but confirm the script is accessible).
- Adjust image scales, text styles, and positions to fit your game's layout.
内容的提问来源于stack exchange,提问作者jurgenizer
相关产品推荐
相关产品推荐

