Added some logic for collision detection

This commit is contained in:
Arne van Iterson 2020-03-11 12:02:53 +01:00
parent 1f096d1ca4
commit e878626d54
4 changed files with 96 additions and 0 deletions

10
lib/Rect.js Normal file
View File

@ -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;

View File

@ -2,6 +2,8 @@ var Container = require("./Container.js"),
CanvasRenderer = require("./renderer/CanvasRenderer.js"), CanvasRenderer = require("./renderer/CanvasRenderer.js"),
Game = require("./Game.js"), Game = require("./Game.js"),
math = require("./utilities/math.js"), math = require("./utilities/math.js"),
entity = require("./utilities/entity.js"),
Rect = require("./Rect.js"),
KeyControls = require("./controls/KeyControls.js"), KeyControls = require("./controls/KeyControls.js"),
MouseControls = require("./controls/MouseControls.js"), MouseControls = require("./controls/MouseControls.js"),
Sprite = require("./Sprite.js"), Sprite = require("./Sprite.js"),
@ -19,6 +21,8 @@ module.exports = {
Container, Container,
Game, Game,
math, math,
entity,
Rect,
KeyControls, KeyControls,
MouseControls, MouseControls,
Sprite, Sprite,

View File

@ -76,6 +76,9 @@ class CanvasRenderer {
0, 0, 0, 0,
child.width, child.height 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 { } else {
ctx.drawImage(img, 0, 0); ctx.drawImage(img, 0, 0);
} }

79
lib/utilities/entity.js Normal file
View File

@ -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
};