boxes/js/entity.mjs

64 lines
1.3 KiB
JavaScript

import * as world from "./world.mjs";
const BOX_SIZE = world.BOX_SIZE;
const entities = [];
export function create (box, x = 0, y = 0, color = "#fff") {
const entity = {
id: entities.length,
box,
x,
y,
color,
};
entities.push(entity);
return entity;
}
export function destroy (id) {
// returns the destroyed entity, idk if that makes sense.
return entities.splice(id, 1)[0];
}
export function for_each (callback) {
entities.forEach(entity => {
callback(entity, entity.id);
});
}
function clamp_pos (entity) {
if (entity.x < 0) entity.x = 0;
if (entity.x >= BOX_SIZE) entity.x = BOX_SIZE - 1;
if (entity.y < 0) entity.y = 0;
if (entity.y >= BOX_SIZE) entity.y = BOX_SIZE - 1;
return entity;
}
export function set_pos (entity, x, y) {
entity.x = x;
entity.y = y;
if (out_of_bounds(entity)) {
if (entity.box.parent) {
entity.box = entity.box.parent;
// TODO: exit from side of box.
}
clamp_pos(entity);
}
if (world.get_tile(entity.box, entity.x, entity.y)?.type === "box") {
entity.box = world.get_tile(entity.box, entity.x, entity.y).box;
// TODO: enter at edge of box.
}
}
export function move (entity, d_x, d_y) {
set_pos(entity, entity.x + d_x, entity.y + d_y);
}
function out_of_bounds (entity) {
return world.out_of_bounds(entity.x, entity.y);
}