Wednesday, November 25, 2015

Small But Important Game Update

Today I took a break from adding any more serious capabilities to my Phaser platformer so that I could focus on a small but important change - the Science Frog images!

I said from the beginning that this was supposed to be a Science Frog game, but so far Science Frog has not been seen. That's because I re-used the frog spritesheet from the soccer game just so I could get stuff working in the code. Drawing the images always takes me a while and I prefer to get the coding first. At some point, though, I have to stop and fix the images.

I did sneak in a few minor code tweaks along with the new images. First of all, I am using half as many images as I was before. I only have pictures of Science Frog facing right. Instead of switching to a reverse animation sequence when he turns around, I am flipping the sprite by setting the scale.x value to be -1 or 1 depending on which direction he is facing.

frog.anchor.setTo(0.5, 0);

// normal direction for the sprites
frog.scale.x = 1;

// reverse direction for the sprites
frog.scale.x = -1;

The important thing here is that for the scale flip to work, the anchor of the sprite has to be 0.5 on the x-axis. Otherwise, the image gets drawn someplace you don't expect!

The other change is to use stop the animation and use only a certain frame when Science Frog is jumping or falling. This stops the effect of him flailing his arms and legs if you hold the arrow keys down while jumping. That just looked weird. For that, I just check to see if the y-velocity is non-zero and then set the sprite's frame accordingly.

function setAnimation(f) {

    if (f.body.velocity.y === 0) {

        // frog is on the ground

        if (f.body.velocity.x === 0) {

            // no animation, the frog is still
            f.animations.stop(null, true);

        } else {

            if (f.body.velocity.x > 0) {
                f.scale.x = 1;
            } else if (f.body.velocity.x < 0) {
                f.scale.x = -1;
            }
            f.animations.play("run");

        }

    } else {  // frog is jumping up or falling down

        // no animation, use a fixed frame
        f.animations.stop(null, true);
        
        if (f.body.velocity.y < 0) {
            f.frame = 1;
        } else if (f.body.velocity.y > 0) {
            f.frame = 2;
        }

    }

}

That's all for today! Remember, you can play the game here, and view the complete source code on GitHub. Have a Happy Thanksgiving, and be sure to read today's comic before you prepare your turkey.

Amphibian.com comic for 25 November 2015