How to switch sprites of a game object?

I have a game object with a spritesheet. The sprite sheet has only two sprites in it, each 64 pixels:

this.load.spritesheet('target', 'assets/sprites/target.png', {
	frameWidth: 64,
	frameHeight: 64
});

...

let targetImg = this.add.image(position.x, position.y, 'target');

I want to be able to switch which frame the game object uses. How do I go about doing that?

Since you are loading a spritesheet all sprite animations should be managed with… well animations.

Goes something like this

this.load.spritesheet('target', 'assets/sprites/target.png', {
	frameWidth: 64,
	frameHeight: 64
});

let targetImg = this.add.sprite( position.x, position.y, 'target' );
targetImg.animations.add('animA',  [ 0, 1 ]);
targetImg.animations.add('animB',   [ 1, 2 ]);
targetImg.animations.play("animA", speed); // "plays" first frame
targetImg.animations.play("animB", speed, true); // "plays" second frame forever

I’m getting Uncaught TypeError: surfaceImage.anims.add is not a function on the line targetImg.animations.add('animA', [ 0, 1 ]);. Am I missing something? Is it the scene’s animations set that I’m supposed to add to? Like this.animations.add(...)?

Oh wait sorry, I didn’t notice that the talk was about Phaser 3

If all you want to do is change the frame, there’s no need for animations. Simply do targetImg.setFrame(1);.

If you would have an atlas, you would instead of frame index supply the asset name.
Alternatively if you want to change the whole texture to something else, it’s img.setTexture(key, frame).

This works! Thank you!