Is there a "clean" way to reverse a sprite's animation when it finishes?

For example, say there is a character in a game with 3 frames for a walking animation (frame 1: left leg forward, frame 2: both legs side by side, frame 3: right leg forward). So it would make sense to simply loop the animation while in the ‘walking state’. The problem is, at the end, the animation will go from frame 3 (right leg forward), back to frame 1 (left leg forward), when it should go back to frame 2, then frame 1. IE,

Should be: [1] [2] [3] [2] [1] [2] [3] [2] [1]
Not: [1] [2] [3] [1] [2] [3] [1] [2] [3]

I easily solved it by simply copying frame 2 (legs side by side), and pasting it as frame 4. So the animation goes 1-2-3-4-1-2-3-4, and its ok because frame 4 is the same as frame 2. But the downside is that it uses an extra frame on my sprite sheet, which I’d prefer not to waste.

So, assuming I just want to use 3 frames, is there a way to ‘reverse’ the animation when it reaches the end, instead of looping back to the first frame? (Hopefully I explained clearly enough)

No worries it is clear :slight_smile:

I think you could leverage sprite.onAnimationEnd callback and then call playAnimation again with “from” and “to” switched?

Yeah, its what I was thinking too. I’m just wishing there was maybe another parameter that could be passed to the sprite’s playAnimation function, ie, reverseAtEndOfLoop. Then in the _animate function Babylon.js/sprite.ts at master · BabylonJS/Babylon.js · GitHub, something like:

if (this._loopAnimation) {
    if (this._reverseAtEndOfLoop) {
        this._direction *= -1;
        let from = this._fromIndex;
        this._fromIndex = this._toIndex;
        this._toIndex = from;
        this._cellIndex += (this._direction > 0 ? 1 : -1);
    } else {
        // normal loop back to start frame
        this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex;
} else {
    // not looping

I think the code is correct, but something like that. I’m using TS and I’m not sure if there is a way to ‘override’ the Sprite._animate function in my project, let alone access the private variables in the Sprite object.

1 Like

You know what? You should do a PR to add that feature!!

Definitely a good one to have

Sure, I could do that

I realized the code I posted is wrong, there is no need to reverse the to and from indices. Anyways, will send a PR tonighr