Documentation Index
Fetch the complete documentation index at: https://mintlify.com/OmarMtya/enginejs-module/llms.txt
Use this file to discover all available pages before exploring further.
motor.js is the heart of Engine.js’s runtime. It contains the animation loop, the rendering pipeline, the physics tick, and the click-detection binder. Most of its exports are attached to the $g global by index.js, so in a plain HTML project you call them as $g.Animar(), $g.DetenerAnimacion(), and so on.
See also: Guides: Animation Loop, Concepts: Physics, and the Environment API for the shared state these functions read and write.
Exported Functions
IniciarAnimacion
Starts the engine’s animation loop. Exposed on the global as$g.Animar.
void
Behaviour (in order):
- Calls the internal
Inicializarfunction, which resolves initial overlaps between figures and plays sounds whoseactivacionis'inicial'. - Snapshots
Environment.figurasintoEnvironment.backupby callingEnvironment.Copyon every figure, so the scene can be fully restored later. - Calls
window.requestAnimationFrame(Step)to begin the loop, storing the returned request ID in the module-privaterequestIdvariable.
DetenerAnimacion
Stops the animation loop and restores the scene to the snapshot taken whenIniciarAnimacion was called. Exposed on the global as $g.DetenerAnimacion.
void
Behaviour (in order):
- Guards against a no-op call: does nothing if
requestIdisundefined(i.e. the loop was never started or is already stopped). - Calls
window.cancelAnimationFrame(requestId)and setsrequestId = undefined. - Replaces
Environment.figuraswith a fresh deep-clone of every figure inEnvironment.backup(viaEnvironment.Copy), reverting all positions, velocities, and physics state to their initial values. - Sets the module-private
animandoflag tofalse. - Pauses every figure whose
transform.sonido.activacion === 'inicial'.
After
DetenerAnimacion returns, the canvas is not automatically cleared or redrawn.
Call $g.Dibujar(true) immediately afterwards if you want to render the reset
state to the screen.Dibujar
Renders the current frame to the canvas. Optionally advances the physics simulation one tick before drawing. Exposed on the global as$g.Dibujar.
When
true (the default), the function draws the current state of all figures without
advancing physics — useful for a static preview or for rendering the initial/restored frame.
When false, physics is advanced via calcularSiguientePaso() after the draw pass.void
Rendering pipeline (executed every call):
- If
sinAvanceisfalseand theanimandoflag is not yet set, callsInicializar()to resolve overlaps before the first frame. - Increments
Environment.contadorby1. - Calls
c.clearRect(0, 0, Environment.anchura, Environment.altura)to wipe the previous frame. - Calls
c.beginPath()to reset the path buffer. - Iterates
Environment.figurasand draws each figure according to itstipo:
tipo | Draw call |
|---|---|
'circulo' | Sets fillStyle, calls arc(x, y, radio, 0, 2π), then fill() |
'cuadrado' | Sets fillStyle, calls fillRect(x, y, anchura, altura), then stroke() |
'imagen' (static) | Calls drawImage(src, 0, 0, src.width, src.height, x, y, anchura, altura) |
'imagen' (sprite) | Delegates to the internal DibujarSprite function |
- If
sinAvanceisfalse, calls the internalcalcularSiguientePasofunction to update positions and physics state.
detectarClick
Attaches or detaches a click handler on the canvas element. On each click, it iterates all figures inEnvironment.figuras and calls Environment.clickListener with every Figura whose bounds contain the click coordinates. Exposed on the global as $g.DetectarClick.
When
true, sets Environment.canvasHTML.onclick to a function that iterates all entries
in Environment.figuras, tests each one with the internal detectarClickFigura utility using
event.offsetX / event.offsetY, and calls Environment.clickListener(figura) for every
figure whose bounds contain the click point.
When false, replaces Environment.canvasHTML.onclick with an empty function, effectively
disabling click detection without removing the property.void
detectarClick reads Environment.canvasHTML to attach the handler. If you initialised
the canvas with InitCanvasStatic (which does not set canvasHTML), you must assign
Environment.canvasHTML manually before calling $g.DetectarClick(true).Step (internal — not on $g)
Step is the requestAnimationFrame callback that drives the loop. It is exported from motor.js but is not attached to $g by index.js.
The high-resolution timestamp provided by the browser’s
requestAnimationFrame API.
The first call captures it in the module-private start variable for potential elapsed-time
calculations.void
Behaviour: Calls Dibujar(false) (draw + advance physics), then schedules itself again with requestAnimationFrame. The loop continues until DetenerAnimacion cancels the pending frame ID.
Error (exported — not on $g)
motor.js exports a function named Error that simply throws the string "EXISTE UN ERROR". It is not attached to $g by index.js and is not part of the public Engine.js API. It exists in the module exports but has no practical use for consumers of the library.
Internal Functions
These functions are defined insidemotor.js but are not exported and are not accessible through $g. They are documented here to make the rendering and physics pipeline fully transparent.
Inicializar
Called once byIniciarAnimacion (and defensively by Dibujar on the first sinAvance = false call) to prepare the scene for simulation.
Behaviour:
- Runs a forward-scan overlap-resolution pass over
Environment.figuras. For each pair of figures that are already touching at rest, the outer figure is pushed to the right along the X axis to eliminate the initial overlap:- Against a
'circulo': pushed tofigura.transform.x - (figura.transform.radio * 3). - Against a
'cuadrado'(outer is circle): pushed to(pivote.transform.x + pivote.transform.radio) + figura.transform.anchura. - Against a
'cuadrado'(outer is square): pushed topivote.transform.x + figura.transform.anchura.
- Against a
- Plays the
HTMLAudioElement(src.play()) for every figure whosetransform.sonido.activacion === 'inicial'.
The overlap resolution is a single forward pass (similar to one iteration of bubble sort on
the X axis). It is not a full constraint solver; complex initial pile-ups may still require
manual positioning.
calcularSiguientePaso
Advances the physics simulation by one tick. Called byDibujar(false) after the draw pass.
Behaviour:
- Clones
Environment.figuras(via spread[...Environment.figuras]) and sorts the clone in descending Y order (highest Y value first). This ensures that figures lower on the canvas process collision responses before figures higher up, preventing tunnelling artefacts. - For each figure in the sorted order:
- Skips figures without a
rigidocomponent. - If
rigido.sinColisionisfalse(collision-enabled): callsfigura.tocandoRigidos(). If no collision was detected (rigido.colision === false), callsfigura.afectarGravedad()andfigura.tocandoFondo(). - If
rigido.sinColisionistrue: calls onlyfigura.afectarGravedad()(gravity without collision detection).
- Skips figures without a
DibujarSprite
Renders the current frame of an animated sprite sheet and advances the frame index based on elapsed wall-clock time. Called by:Dibujar, when figura.tipo === 'imagen' and figura.transform.imagen.sprite is set.
Behaviour:
- Reads
src(theHTMLImageElement) andsprite(theSpriteconfig object) fromtransform.imagen. - Calculates the source X offset as
sprite.anchura * sprite.frame.valor— each frame issprite.anchurapixels wide on the sheet. - Calls
c.drawImage(src, frameX, sprite.altura * sprite.row, sprite.anchura, sprite.altura, transform.x, transform.y, sprite.anchura, sprite.altura)to blit the current frame onto the canvas. - Checks whether
sprite.velocidad * 1000milliseconds have elapsed sincesprite.frame.ultimo. If so, advancessprite.frame.valorby1modulosprite.cols(looping back to frame 0 after the last column) and records the new timestamp insprite.frame.ultimo.