Crouching in 2D platformer

Hi all, I’m having a bit of an issue with making a character in a 2D platformer crouch properly. My goal is to have my sprite crouch when I press the down key. Normally, the character is 36x50 pixels. When crouching, the sprite is 50x32 pixels.

hannah_upright
hannah_crouch

That being said, this game requires that crouching is not possible while in the air (jumping, falling, etc). But when I call setSize(50, 32) on my sprite, there is a small interval where my character will fall until it reaches the tile beneath it. That results in the sprite flashing between the crouching and standing positions as it tries to crouch but never reaches the ground beneath it. I can use an offset to prevent the falling, but then the image appears off as shown above.

See my code below:

        // Handle animation
        if (onGround) {
            if (controls.left.isDown || controls.right.isDown) {
                sprite.body.setSize(32, 50, false).setOffset(0, 0);
                sprite.anims.play('walk', true);
            } else if (controls.down.isDown) {
                sprite.body.setSize(50, 32, false).setOffset(0, 18);
                sprite.anims.play('crouch', true);
            } else {
                sprite.body.setSize(32, 50, false).setOffset(0, 0);
                sprite.anims.play('idle', true);
            }
        }

Is there a way I can simultaneously preventing crouching while off the ground, and also gracefully crouch from a standing position?

Probably you have to adjust body.y instead of the offset, and so also save the crouched state.