Character animation and movement

Animating a character’s movement does not require frames for each direction the character is facing. Instead, you can use character.scale.x to mirror the image and make it face the other way without unnecessary bloating of spritesheet.

"use strict";
window.AnimateCharacter.state.menu = {
    create: function() {
        //create cursor keys and game objects
        this.cursors = this.game.input.keyboard.createCursorKeys();
        this.character = mt.create("character");
        this.ground = mt.create("ground");

        //add animations for character
        this.character.animations.add('stand', [0, 1, 2, 3], 10, true);
        this.character.animations.add('run', [6, 7, 8, 9, 10, 11], 10, true);
        this.character.animations.add('jump', [12, 13], 10, false);
        this.character.animations.play('stand');
    },

    update: function() {
        //intoduce a variable to distinguish between the character being on ground or in the air
        var standing = false;

        //collision check
        this.game.physics.arcade.collide(this.character, this.ground.self, function(character, ground) {
            //sets character to being on ground if it is touching the top of the ground blocks
            if (ground.body.touching.up) {
                standing = true;
            } else standing = false;
            if (this.cursors.up.isDown) {
                if (ground.body.touching.up) {
                    this.character.animations.play('jump');
                    this.character.body.velocity.y = -550;
                    standing = false;
                }
            }
        }, null, this);

        //run animations use scale.x=-1 to mirror the character sprite
        if (this.cursors.left.isDown) {
            this.character.body.velocity.x = -200;
            if (standing) this.character.animations.play('run');
            this.character.scale.x = -1;
        } else if (this.cursors.right.isDown) {
            this.character.body.velocity.x = 200;
            if (standing) this.character.animations.play('run');
            this.character.scale.x = 1;
        } else {
            this.character.body.velocity.x = 0;
            if (standing) this.character.animations.play('stand');
        }

    }
};

Full sample available here.

Leave a Reply

Your email address will not be published. Required fields are marked *