Button with custom images

I’m trying to create a button class with custom images. In particular, this class should be able to get, as input, an image and change the tint and alpha in different stages (pressed, unpressed).

What I found out is that I can have my button class extends Phaser.GameObjects.Image and listened to the mouse event and make the correct changes.

The problem is that Image’s constructor takes a texture and a frame parameter. So, in other to custom my image, I’ll have to create a texture. The only way I know how to do so is to prepare a json file together with the image file and load the texture in preload using this.load.atlas. This is inconvenient for my purpose, though, as I want to be able to use this button class through many scenes with random images from a large bank. Having to prepare the json for each of the images seems like a bad solution.

Is there a way to write my class so that it take an image instead of a pair of texture and frame?

You can always use an image instead of a texture and frame.
Divide your texture to individual images and only use it’s key. :wink:

1 Like

To elaborate on sazzadh’s reply - all images that you load are internally stored as textures. When a Game Object such as an Image asks you for a texture and a frame, it’s really just asking you for a key; in this.add.image(0, 0, 'image'), 'image' is the texture key and the frame is left blank, which will make it use the first (and only if it’s an image) frame of the texture.

If you want to use a loaded image (i.e. one you’ve loaded with this.load.image), pass its key as the texture parameter and leave the frame blank. You don’t need to deal with sprite sheets or atlases unless you want multiple frames in the image.

That said, I can’t tell from your description whether you want to avoid loading the images at all or if you just want to avoid atlases. If you’re actually going for the former, it won’t work. Any external asset has to be explicitly loaded and processed by Phaser before it can be used, especially under the WebGL renderer.

1 Like