Sometimes the game starts without waiting for all the assets to load. This happens most often with the spaceStation
which is the largest sprite at 3372x700 px. When the game first boots, the spaceStation
isn’t loaded. But if you leave the game then come back to it without refreshing the page, it will be loaded the second time.
The game is hosted here so you can see what I mean: https://seanhetzel.github.io/star-runner/#/
Here is my code for the spaceStation
sprite:
import spaceStation from "../assets/space-station-sprite-sheet.png";
// other stuff...
preload: function() {
// other stuff...
const spaceStationImg = new Image();
spaceStationImg.onload = () => {
this.textures.addSpriteSheet("spaceStation", spaceStationImg, {
frameWidth: 3372,
frameHeight: 700
});
};
spaceStationImg.src = spaceStation;
// other stuff...
}
// other stuff...
create: function() {
// other stuff...
const config = {
key: "lights",
frames: this.anims.generateFrameNumbers("spaceStation", {
start: 0,
end: 6
}),
frameRate: 3,
repeat: -1
};
this.anims.create(config);
this.spaceStation = this.impact.add
.sprite(1686, 350, "spaceStation")
.play("lights")
.setDepth(1);
// other stuff...
}
Am I not loading it correctly?
Thanks!
I don’t think so. It looks like you’re trying to involve vanilla Javascript methods, which is unnecessary. Phaser 3 can take care of it all for you.
All you need to have in your preload()
function is:
this.load.spritesheet(
'spaceStation',
'../assets/space-station-sprite-sheet.png',
{
frameWidth:3372,
frameHeight:700
}
);
The rest should still function as it is.
1 Like
Thanks for the reply.
That didn’t seem to work however. When I modified that in the preload()
function, the sprite stopped loading entirely for some reason. That is, when I left the game then came back, it still wasn’t loading. I tried refreshing and coming back dozens of times both locally and online and couldn’t get the spaceStation
to load.
I’m not sure why that’s not working. Was the network request for the image file still being executed? I’m pretty sure the code I posted is the correct approach and it’s just a detail or two that are off.
Using the Phaser 3 Loader ensures the create()
function doesn’t get called until all the requested resources are loaded. The way you’re doing it, you’re making an asynchronous call to load the image - which doesn’t prevent Phaser from carrying on with executing create()
.
That makes perfect sense. Your approach is correct and I just had one detail off. I got it to work just by using the import from the react component instead of pointing to the relative path.
this.load.spritesheet(
'spaceStation',
spaceStation,
{
frameWidth:3372,
frameHeight:700
}
);
Now it’s getting the sprite from import spaceStation from "../assets/space-station-sprite-sheet.png";
import instead of directly pointing to the relative path and using the Phaser 3 Loader.
Thanks for the help!