diff --git a/lib/Rect.js b/lib/Rect.js new file mode 100644 index 0000000..3fe7d8f --- /dev/null +++ b/lib/Rect.js @@ -0,0 +1,10 @@ +class Rect { + constructor(w, h, style = { fill: "#333" }) { + this.pos = { x: 0, y: 0 }; + this.w = w; + this.h = h; + this.style = style; + } + } + +module.exports = Rect; \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index 3298502..a8bf2b1 100644 --- a/lib/index.js +++ b/lib/index.js @@ -2,6 +2,8 @@ var Container = require("./Container.js"), CanvasRenderer = require("./renderer/CanvasRenderer.js"), Game = require("./Game.js"), math = require("./utilities/math.js"), + entity = require("./utilities/entity.js"), + Rect = require("./Rect.js"), KeyControls = require("./controls/KeyControls.js"), MouseControls = require("./controls/MouseControls.js"), Sprite = require("./Sprite.js"), @@ -19,6 +21,8 @@ module.exports = { Container, Game, math, + entity, + Rect, KeyControls, MouseControls, Sprite, diff --git a/lib/renderer/CanvasRenderer.js b/lib/renderer/CanvasRenderer.js index 1867e11..3b2ec42 100644 --- a/lib/renderer/CanvasRenderer.js +++ b/lib/renderer/CanvasRenderer.js @@ -76,6 +76,9 @@ class CanvasRenderer { 0, 0, child.width, child.height ); + } else if (child.style && child.w && child.h) { + ctx.fillStyle = child.style.fill; + ctx.fillRect(0, 0, child.w, child.h) } else { ctx.drawImage(img, 0, 0); } diff --git a/lib/utilities/entity.js b/lib/utilities/entity.js new file mode 100644 index 0000000..857f851 --- /dev/null +++ b/lib/utilities/entity.js @@ -0,0 +1,79 @@ +const math = require('./math'); +const Rect = require('../Rect'); + +function addDebug(e) { + e.children = e.children || []; + const bb = new Rect(e.w, e.h, { fill: "rgba(255, 0, 0, 0.3)" }); + e.children.push(bb); + if (e.hitBox) { + const { x, y, w, h } = e.hitBox; + const hb = new Rect(w, h, { fill: "rgba(255, 0, 0, 0.5)" }); + hb.pos.x = x; + hb.pos.y = y; + e.children.push(hb); + } + return e; +} + +function angle(a, b) { + return math.angle(center(a), center(b)); +} + +function bounds(entity) { + const { w, h, pos, hitBox } = entity; + const hit = hitBox || { x: 0, y: 0, w, h }; + return { + x: hit.x + pos.x, + y: hit.y + pos.y, + w: hit.w - 1, + h: hit.h - 1 + }; +} + +function center(entity) { + const { pos, w, h } = entity; + return { + x: pos.x + w / 2, + y: pos.y + h / 2 + }; +} + +function distance(a, b) { + return math.distance(center(a), center(b)); +} + +function hit(e1, e2) { + const a = bounds(e1); + const b = bounds(e2); + return ( + a.x + a.w >= b.x && + a.x <= b.x + b.w && + a.y + a.h >= b.y && + a.y <= b.y + b.h + ); +} + +function hits(entity, container, hitCallback) { + const a = bounds(entity); + container.map(e2 => { + const b = bounds(e2); + if ( + a.x + a.w >= b.x && + a.x <= b.x + b.w && + a.y + a.h >= b.y && + a.y <= b.y + b.h + ) { + hitCallback(e2); + } + }); +} + +module.exports = { + addDebug, + angle, + bounds, + center, + distance, + hit, + hits +}; \ No newline at end of file