How do I capture the current frame number of an animation?
I want to use it to start another animation in the same frame. How do I start an animation in a particular frame?
Hey bobbin,
You can do this by storing a local variable that keeps track of your current frame, then in an update loop, check to see if the currentFrame of the animation differs from your local current frame. If it differs and is the frame you want to start an additional animation on, then do so.
Here’s some sample code:
constructor()
{
this.curFrameIdx = 0;
this.destinationFrame = 10; //This is the frame you'll want to spawn an animation on.
this.animatedImg = this.add.sprite(x, y, "myAtlas", "startingFrame"); //this = scene
}
update()
{
if(this.curFrameIdx != this.animatedImg.anims.currentFrame.index)
{
this.curFrameIdx = this.animatedImg.anims.currentFrame.index;
if(this.curFrameIdx === this.destinationFrame)
{
//START YOUR ANIMATION
}
}
}
Note: This is pseudo code and likely will not work if copy + pasted. The code in the constructor()
can be placed in your create()
method if you are running this directly from a Scene
Thanks for your reply.
My code is different so I don’t have access to currentFrame from my anim. I suppose it’s from creating the anim from a spritesheet and not an atlas. I’ll have to check it out.
All sprites have an anims
property and if there is an animation playing on the sprite, the currentFrame
property will not be null. Perhaps the animation isn’t setup fully and you’re getting an error? In that case, I would add an additional condition such as:
if(this.animatedImg.anims != null && this.animatedImg.anims.currentFrame != null)
Oh, thanks. I have currentFrame. I trusted too much on autocomplete.
Thanks a lot.
another question if you don’t mind.
I was trying to change
this.animatedImg.anims.currentFrame.index
To jump to another frame in the animation. It doesn’t work.
also tried with:
player.anims.currentAnim.setFrame(myFrame)
throws an error
How do you change frames on the animation?