precision-game/js/enemy.mjs
2023-10-27 20:53:28 +02:00

79 lines
1.6 KiB
JavaScript

import * as entity from "./entity.mjs";
import { register_tick } from "./tick.mjs";
import * as behaviours from "./behaviours/main.mjs";
import * as Entity from "./entity.mjs";
import { get_player } from "./player.mjs";
import * as Event from "./event.mjs";
const enemies = [];
function tick_enemy (enemy, deltatime) {
const meta = entity.get_meta(enemy);
const age = meta.get("age") + deltatime;
meta.set("age", age);
if (meta.has("behaviour")) {
const b = meta.get("behaviour");
if (behaviours.exists(b)) { const callback = behaviours.get_tick(b);
callback(enemy, deltatime);
}
}
if (Entity.touches(enemy, get_player())) {
Event.trigger("level/restart");
}
}
register_tick(deltatime => {
for (const enemy of enemies) {
tick_enemy(enemy, deltatime);
}
});
export function get_all () {
return enemies;
}
export function create (...args) {
const enemy = entity.create(...args);
const meta = entity.get_meta(enemy);
meta.set("age", 0);
return enemy;
}
export function add (enemy) {
enemies.push(enemy);
}
function remove_all () {
enemies.splice(0, enemies.length);
}
Event.listen("level/unload", _ => {
remove_all();
});
Event.listen("level/load/enemy", enemies => {
for (const data of enemies) {
const {pos, size} = data;
const enemy = create(pos[0], pos[1], size[0], size[1]);
if (data.hasOwnProperty("behaviour")) {
behaviours.init(enemy, data.behaviour, Object.fromEntries(data.meta));
}
const meta = Entity.get_meta(enemy);
if (data.hasOwnProperty("meta")) {
for (const [key, value] of data.meta) {
meta.set(key, value);
}
}
add(enemy);
}
})