game_actor_component_drawable_component.js
import ActorComponent from "./actor_component.js";
import Sprite from "../../../registry/sprite/sprite.js";
import Vec2 from "../../vector/vec2.js";
import Bounds from "../../vector/bounds.js";
/**
* @module DrawComponent
* @fileoverview Contains DrawComponent class.
*/
/**
* @class
* @extends ActorComponent
*/
class DrawableComponent extends ActorComponent {
/**
* Create a new drawable component.
* @param {string|Sprite} sprite Sprite or identifier of sprite to use
* @param {number} opacity Transparency of sprite
* @constructor
*/
constructor({
sprite = null,
opacity = 1
} = {}) {
super();
this._sprite = null;
this.sprite = sprite;
this.opacity = opacity;
}
//
// Getters
//
/**
* Get the sprite being used.
* @returns {Sprite|null} Sprite being used for drawing
*/
get sprite() {
return this._sprite;
}
/**
* Get the bounds of the sprite being used.
* @returns {Bounds} Bounding box of sprite
*/
get bounds() {
return Bounds.fromWidthAndHeight(this.sprite.width, this.sprite.height);
}
//
// Setters
//
/**
* Set the sprite for drawing.
* @param {string|Sprite} sprite Sprite or identifier of sprite to use
*/
set sprite(sprite) {
if (sprite !== null) {
if (typeof sprite === "string") {
const check = $$.reg.sprites.get(sprite);
if (check !== null)
this._sprite = check;
} else if (sprite instanceof Sprite)
this._sprite = sprite;
} else {
this._sprite = null;
}
}
//
// Update & Draw
//
draw(ctx) {
if (this._sprite === null)
return;
const w = this._sprite.width;
const h = this._sprite.height;
if (this.actor.shadow)
this.actor.setShadow(ctx);
ctx.save();
ctx.globalAlpha = this.opacity;
this._sprite.draw(ctx, new Vec2(-w / 2, -h / 2));
ctx.restore();
this.actor.resetShadow(ctx);
}
}
export default DrawableComponent;