Documentazione BeeEngine

Documentazione – BeeEngine
BeeEngine v2.8.0

BeeEngine — Documentazione Tecnica

Facade e core loop: start / pause / stop, scene, tween, timer, prefab, pathfinder

BeeEngine Mascot

Panoramica

BeeEngine è la facciata. Vive in BeeEngine.js (radice del package); index.js è solo export * from './BeeEngine.js'. Non è una scena, non è un’entity, non è il collision system. Costruisce i sottosistemi, tiene il canvas e fa girare un requestAnimationFrame. I moduli (time, scenes, tweens, timers, physics, pools, prefabs, pathfinder, ladybug) non si auto-avviano: li chiama il loop, in un ordine fisso — oppure li chiami tu.

Quello che non è: un ECS, un scene graph proprietario, un runner di collisions.run(). Le entity stanno in due liste (motore o scena). Il disegno lo fa BeeLayer (raccoglie entrambe). Le collisioni a gruppi le lanci tu, di solito da scene.update.

Il costruttore vuole un canvas (id stringa o elemento). Senza elemento lancia. Larghezza/altezza default 800×600. Crea subito assets, input, scenes, time, timers, tweens, physics, pools (con pool bullet), prefabs (type di stock), pathfinder, audio, ui, save, debug (Ladybug già attach). camera e grid restano null finché non le assegni.

import { BeeEngine } from 'beeengine';

const gioco = new BeeEngine('testCanvas', 800, 600);

gioco.scenes.add('main', scena);
gioco.scenes.change('main');
gioco.start();

Il loop — un rAF, un ordine

Ogni frame, se isRunning è true. time.tick è sempre il primo: da lì nascono dt (0 in pausa) e unscaledDt. Poi i clock e l’audio; poi, solo se non in pausa, il mondo; poi il callback utente (anche in pausa); poi clear + draw; infine input.endFrame() e il prossimo rAF.

Ordine reale di loop(timestamp). La pausa ferma scene, entity e fisica. I clock vengono comunque tick-ati: i timer/tween scalati vedono dt = 0, quelli unscaled no. Il callback update e il draw girano sempre.

  1. 1. orologitime.tick → timers.tick → tweens.tick → audio.update
  2. 2. mondoSe non in pausa: scenes.update, updateEntities, physics.step a passo fisso
  3. 3. hookthis.update(dt, input, time) sempre, poi ui.update
  4. 4. drawclear, camera, drawWorld, layer mondo, render, restore, layer screen, UI, overlay, endFrame

Draw mondo (sotto ctx.save + camera): scenes.drawWorld → layers.drawWorld (raccoglie currentScene.entities e engine.entities) → callback render → overlay mondo di Ladybug. Dopo restore: layer screen, scenes.drawUI (scene.draw), ui.draw, touch overlay, overlay Ladybug + poll.

collisions.run() non è nel loop. La demo lo chiama da scene.update. Senza quella riga i gruppi restano configurati e inerti. pathfinder e prefabs non tickano da soli: li chiami tu (chase, spawn).

start / stop / pause / resume

Chiamata rAF time.paused Mondo (scene / entity / physics)
start(update?, render?) parte se !isRunning resume + begin gira dal frame dopo
pause() / isPaused = true continua true → dt = 0 saltato
resume() / isPaused = false se era spento, riparte false gira
stop() cancel, isRunning = false true fermo (niente frame)

start se è già running è no-op: non cambia i callback. I callback validi vengono salvati in _savedUpdate / _savedRender; una start() senza argomenti li riattacca. Il warning «nessun update/render/SceneManager» è morto: il costruttore crea sempre this.scenes, quindi start() da solo è legale (come fa la demo).

pause non è stop. F4 di Ladybug è time.togglePause() sullo stesso flag. In pausa il callback this.update gira ancora (con dt = 0): menu di pausa e input restano vivi. resume() dopo uno stop() riaccende il rAF perché this.scenes esiste sempre — non serve un secondo start().

setTimeScale(scale) è time.setScale. I timer/tween scalati seguono; quelli unscaled no.

addEntity vs scenes

Due liste, un ingresso. addEntity(entity) rifiuta null / destroyed, non duplica il reference.

Condizione Dove finisce Chi la ticka
C’è scenes.currentScene scene.entities (+ entity.scene / engine) scenes.update → #tickEntities
Nessuna scena corrente engine.entities updateEntities

Il loop chiama entrambe: prima scenes.update, poi updateEntities. Se usi solo addEntity le liste restano disgiunte. Se pushti a mano nello stesso array due volte, o in tutte e due le liste, l’entity prende due update nello stesso frame.

setScene(name, data) chiama destroy() su ogni entity di engine.entities che lo espone, poi svuota l’array, poi scenes.change. change è replace: esce la vecchia (sweep + entity.destroy, salvo persistEntities), entra la nuova. Stesso nome = restart. Un change dentro scene.update salta il tick entity della nuova scena fino al frame dopo.

I children di un prefab nascono con addToScene: false: li tiene il parent, non le liste. BeeLayer.collect cammina i children dal root. Il draw non passa da renderEntities (è un alias di layers.drawWorld): il loop chiama i layer direttamente.

Input

this.input = new BeeInput(this.canvas) nel costruttore. Tastiera (window), mouse e touch (canvas, coordinate scalate sul backing store). Il loop passa input a scene, entity, callback update e ui.update. In fondo al frame: input.endFrame() azzera pressed e mouse.wasPressed — leggerli dopo il draw è tardi.

enableTouchControls() / enableJoystick() sostituiscono this.touchControls (destroy del precedente se c’è). Il joystick ignora l’oggetto options. Il overlay si disegna dopo l’UI, in spazio schermo. BeeInput non ha destroy: i listener restano anche dopo gioco.destroy().

Resize

enableAutoResize(baseW, baseH, reservedHeight) lettera il canvas in CSS (style.width/height), non tocca canvas.width/height né ui. Il backing store resta 800×600 (o quello del costruttore); BeeInput.getCanvasPosition ricalcola dal getBoundingClientRect, quindi il click resta allineato. Una seconda chiamata stacca il listener precedente e ne registra uno nuovo (niente doppio resize). destroy toglie quello corrente.

Collisioni

this.collisions è un BeeCollisionSystem. this.physics è un BeePhysicsWorld a parte (this.spatial è physics.hash). Il loop fa lo step della world a fixedDelta; non chiama collisions.run().

Contratto dei gruppi (come la demo): setGroup / solid / overlap in enter, run() in scene.update (quindi solo se non in pausa). checkCollision(a, b) è AABB nudo su x/y/width/height — fallback se l’entity non ha collidesWith.

destroy

destroy() fa stop, poi scenes.destroy (leave + sweep di tutte le scene), entities.length = 0 senza destroy sulle entity rimaste solo nel motore (diverso da setScene), events = {}. Stacca resize e unlock audio, distrugge debug / audio / ui, clear su timers, tweens, physics, pools. bullets diventa null.

Non tocca: listener di BeeInput, touchControls.destroy, collisions.clear, pathfinder, layer, camera. _startAudioHandler è un residuo: l’unlock vero è _audioUnlock (pointerdown + keydown).

API pubblica — timer, tween, spawn, prefab, pathfinder

I wrapper agganciano i clock del motore. Non crearne di paralleli se vuoi che pausa e timeScale restino unificati.

Metodo Clock / owner Nota
after(duration, onComplete, options?) timers Una volta. autoStart: true. Duration in secondi.
every(duration, onComplete, options?) timers Come after + loop: true.
to / from / fromTo tweens Terzo argomento: numero (duration) o options. Clock iniettato.
timeline(options?) tweens new BeeTimeline({ …options, clock: this.tweens })
createPool(name, options) / pool(name) pools Map Name vuoto lancia. pool sconosciuto → null.
spawn(name, …args) pool nominato acquire + addEntity se ha update. Pool assente → null. Non è il prefab.
prefabs.define / prefabs.spawn this.prefabs Catalogo. Type di stock: entity, enemy, player, shooter, platform, collectible, text.
pathfinder / setGrid(grid) this.pathfinder setGrid salva this.grid e chiama useGrid. Fluent.
enableLadybug(options?) this.debug configure.attach.show. F2 overlay, F3 slow-mo, F4 freeze (= pause).

Altri ingressi: loadAsset / loadManifest / getAsset delegano ad assets. playSound / playMusic al mixer (BEE_BUS.SFX / music). on / emit / off sono un bus in-memory (this.events), non il DOM. lockOrientation è best-effort (screen.orientation.lock, catch vuoto).

Dove è facile sbagliare

gioco.spawn ≠ gioco.prefabs.spawn. Il primo è il pool (createPool). Il secondo è la ricetta. Non sono alias.

collisions.run() non è automatico. Senza chiamarlo in scene.update (o nel callback), solid/overlap non partono. La fisica impulsiva (BeePhysicsWorld) invece sì: la chiama il loop.

Pausa ≠ stop. pause tiene il rAF e il callback update. stop spegne il frame. Il menu di pausa va nel callback utente (o in UI), non in scene.update — quello viene saltato. Dopo stop, resume() riaccende il loop da solo.

Due liste. Con scena corrente addEntity non scrive engine.entities. setScene distrugge e svuota la lista motore; destroy() del motore, invece, svuota senza entity.destroy.

start mentre gira è muto. Per cambiare update/render: stop poi start(nuovo), oppure assegna gioco.update a mano.

Resize CSS, input residuo. Letterbox, non cambio di risoluzione logica. Una seconda enableAutoResize sostituisce il listener. destroy non stacca BeeInput né touchControls.

Esempio: scena, loop, API

import { BeeEngine, BeeGrid } from 'beeengine';

const gioco = new BeeEngine('testCanvas', 800, 600);
gioco.enableAutoResize(800, 600);
gioco.setGrid(new BeeGrid(25, 18, 32));

const main = {
    entities: [],
    enter() {
        gioco.prefabs.define('hero', { type: 'player', x: 100, y: 300 });
        const hero = gioco.prefabs.spawn('hero');
        gioco.collisions.setGroup('player', [hero]);
    },
    update() {
        gioco.collisions.run();
    }
};

gioco.scenes.add('main', main);
gioco.scenes.change('main');

gioco.after(2, () => gioco.emit('ready'));
gioco.to(gioco.ui, { alpha: 1 }, 0.4);

gioco.start((dt, input) => {
    if (input.wasPressed('KeyP')) {
        gioco.isPaused = !gioco.isPaused;
    }
});

Riepilogo API

Fluent: pause, resume, setTimeScale, setGrid ritornano this. Il barrel re-esporta la classe e tutti i moduli (entity, tween, ladybug, physics, UI, …).

Membro Ritorna Scopo
new BeeEngine(canvasId, w?, h?) BeeEngine Canvas obbligatorio. Costruisce i sottosistemi. Ladybug attach.
start(update?, render?) — Avvia rAF. Già running → no-op. Senza callback usa i salvati o solo le scene.
stop() — Cancel rAF + time.pause. Non distrugge nulla.
pause() / resume() / isPaused this / boolean Flag su time. resume può riaccendere il loop dopo stop.
setTimeScale(scale) this Delega a time.setScale.
addEntity(entity) entity Scena corrente o engine.entities. Skip se destroyed.
setScene(name, data?) — Distrugge le entity del motore, svuota la lista, poi scenes.change.
setGrid(grid) this Salva grid; se truthy, pathfinder.useGrid.
after / every BeeTimer Clock timers, autoStart.
to / from / fromTo / timeline tween / timeline Clock tweens.
createPool / pool / spawn pool / item / null Pool nominato. spawn ≠ prefab.
prefabs / pathfinder istanze Un catalogo e un navigatore per motore.
enableAutoResize / enableTouchControls / enableJoystick void / overlay CSS letterbox (listener sostituito se richiami); overlay touch. Joystick ignora options.
enableLadybug(options?) BeeLadybug configure + attach + show.
loadAsset / getAsset / playSound / playMusic promise / asset / voice Assets e mixer.
on / emit / off — Bus this.events.
checkCollision(a, b) boolean AABB. Usato da overlap se manca collidesWith.
destroy() — Stop + sweep scene + clear clock/physics/pools. Input e touch overlay restano agganciati. Entity solo-motore: array svuotato, niente destroy.
time scenes input physics collisions layers audio ui debug istanze Sottosistemi pubblici. spatial = physics.hash.