registry_sprite_layered_sprite.js

import Vec2 from "../../game/vector/vec2.js";

class LayeredSprite {
    /**
     * Create a new sprite partition.
     * @param {SpritePartition[]} sprites Sprite partitions to draw
     * @constructor
     */
    constructor({
        sprites = []
    } = {}) {
        this._sprites = [...sprites];

        this._width = 0;
        this._height = 0;

        for (const sprite of this._sprites) {
            if (sprite.width > this._width)
                this._width = sprite.width;
            if (sprite.height > this._height)
                this._height = sprite.height;
        }
    }


    //
    // Getters
    //

    /**
     * Get the width of the sprite.
     * @returns {number} Width of sprite
     */
    get width() {
        return this._width;
    }

    /**
     * Get the height of the sprite.
     * @returns {number} Height of sprite
     */
    get height() {
        return this._height;
    }


    //
    // Update & Draw
    //

    /**
     * Update the sprite.
     * @param {number} elapsed Time since last update cycle in seconds
     */
    update(elapsed) {}

    /**
     * Draw the sprite.
     * @param {CanvasRenderingContext2D} ctx
     * @param {Vec2} pos Position/offset to draw sprite at
     * @param {Vec2|null} size Custom size of drawn sprite (or null to use default)
     */
    draw(ctx, pos, size = null) {
        if (size === null)
            size = new Vec2(this.width, this.height);

        let i = 0;

        for (const sprite of this._sprites) {
            sprite.draw(ctx, pos.subv(i, i), size.addv(i * 2, i * 2));

            i++;
        }
    }
}

export default LayeredSprite;