Jump to content

Change sprite animation color


Aquarius
 Share

Recommended Posts

Hello,

I just want to share with you my solution to process some image operation on a sprite with animation.

Note that I am working on Typescript so, you maybe have to transpile this code in pure javascript.

I created a class that extend Phaser.Sprite.

In this class after initializing the sprite :

- i create a bitmap, that will not be added to the world, a the size of the spritesheet image and load the spritesheet image in the bitmap

- i load this bitmap as a textureAtlas

then I load the texture.

To change color

I modify the bitmap, then reload the terxture as Atlas an reload texture. (it is possible to set a different texture key in order to keep old state)

As operating transformation on bitmap may be costly, it may be preferable to pre-run these transformations.


class PlayerSprite extends Phaser.Sprite {
    private frameData: any;
    private bitmapBrother: Phaser.BitmapData


    constructor(key: string, position: Phaser.Point, game: Phaser.Game) {
        super(game, position.x, position.y - 32, null);

        this.createBitMap()
            .loadBitmapAsTextureAtlas()
            .loadTexture('heroes-sprites');

        this.animations.add("down", ["sprite1", "sprite2", "sprite3"], 5, true);
        this.animations.add("left", ["sprite13", "sprite14", "sprite15"], 5, true);
        this.animations.add("right", ["sprite25", "sprite26", "sprite27"], 5, true);
        this.animations.add("up", ["sprite37", "sprite38", "sprite39"], 5, true);
        this.animations.add("stand-down", ["sprite2"], 5, true);
        this.play("stand-down");
    }

    createBitMap() {
        let game = this.game;
        let cache = game.cache;
        let cacheSpriteSheet: any = cache.getImage('heroes-sprites', true);
        let bitmapBrother = game.add.bitmapData(cacheSpriteSheet.width, cacheSpriteSheet.height);
        this.bitmapBrother = bitmapBrother;
        this.frameData = cache.getJSON('heroes-sprites-atlas');
        bitmapBrother.load('heroes-sprites');
        return this;
    }
    loadBitmapAsTextureAtlas(prefix?) {
        this.game.cache.addTextureAtlas('heroes-sprites' + prefix, '', this.bitmapBrother.canvas, this.frameData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);
        return this;
    }

    modifiyBitmap() {
        this.bitmapBrother.shiftHSL(0.1);
        return this;
    }


    changeColor() {
        this.modifiyBitmap()
            .loadBitmapAsTextureAtlas('changed')
            .loadTexture('heroes-sprites' + 'changed');
    }
}

 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...