
Security News
Feross on TBPN: How North Korea Hijacked Axios
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.
atomic-game-engine2d
Advanced tools
A lightweight 2D game engine for web browsers with ECS architecture
Un motor de juegos 2D ligero y modular para navegadores web, construido con TypeScript y diseñado con una arquitectura ECS (Entity-Component-System).
⚡ Core Modular
🎨 Renderizado
🔄 ECS (Entity-Component-System)
🎮 Input y Física
Core del Engine
Sistema de Renderizado
ECS (Entity-Component-System)
Input y Física
Script Component (v0.5.1)
examples/script-component/npm install atomic-game-engine2d
Primero, necesitas un canvas en tu HTML:
<!DOCTYPE html>
<html>
<head>
<title>Mi Juego 2D</title>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script type="module" src="game.js"></script>
</body>
</html>
import { GameEngine } from "atomic-game-engine2d";
import { Scene } from "atomic-game-engine2d/core/Scene";
import { Entity } from "atomic-game-engine2d/ecs/Entity";
import { EventSystem } from "atomic-game-engine2d/core/EventSystem";
import { RenderSystem } from "atomic-game-engine2d/graphics";
import { InputManager, InputSystem } from "atomic-game-engine2d/input";
import { INPUT_EVENTS } from "atomic-game-engine2d/types/event-const";
class MiJuego {
private engine: GameEngine;
private player: Entity;
private eventSystem: EventSystem;
private inputSystem: InputSystem;
private inputManager: InputManager;
constructor() {
// 1. Obtener el canvas
const canvas = document.getElementById("gameCanvas") as HTMLCanvasElement;
// 2. Configurar Input Manager
this.inputManager = InputManager.getInstance();
this.inputManager.initialize({
canvas,
preventDefaultKeys: ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"],
enableKeyboard: true,
enableMouse: true,
});
// 3. Crear sistemas
this.inputSystem = new InputSystem();
this.eventSystem = EventSystem.getInstance();
// 4. Configurar el motor
this.engine = new GameEngine({
canvas,
width: 800,
height: 600,
renderer: "canvas2d",
debug: false,
});
}
async initialize() {
// 1. Crear escena
const gameScene = new Scene("game");
// 2. Registrar sistemas ANTES de inicializar
this.engine.addSystem(new RenderSystem());
this.engine.addSystem(this.inputSystem);
// 3. Registrar escena
this.engine.addScene(gameScene);
this.engine.setActiveScene("game");
// 4. Inicializar motor
await this.engine.initialize();
// 5. Crear entidades
this.createPlayer();
// 6. Configurar controles
this.setupControls();
// 7. Iniciar el juego
this.engine.start();
}
private createPlayer() {
this.player = new Entity("player");
// Posición del jugador
this.player.addComponent({
type: "transform",
position: { x: 400, y: 300 },
rotation: 0,
scale: { x: 1, y: 1 },
});
// Apariencia del jugador
this.player.addComponent({
type: "rectangle",
width: 50,
height: 50,
color: "#3498db",
});
// Añadir a la escena activa
this.engine.getActiveScene().addEntity(this.player);
}
private setupControls() {
this.eventSystem.on(INPUT_EVENTS.KEYDOWN, (event) => {
const keyData = event.data as { code: string };
const transform = this.player.getComponent("transform");
if (!transform) return;
const speed = 5;
switch (keyData.code) {
case "ArrowUp":
transform.position.y -= speed;
break;
case "ArrowDown":
transform.position.y += speed;
break;
case "ArrowLeft":
transform.position.x -= speed;
break;
case "ArrowRight":
transform.position.x += speed;
break;
}
});
}
}
// Iniciar el juego
const game = new MiJuego();
game.initialize();
// Crear una entidad
const enemy = new Entity("enemy");
// Añadir componentes
enemy.addComponent({
type: "transform",
position: { x: 100, y: 100 },
rotation: 0,
scale: { x: 1, y: 1 },
});
enemy.addComponent({
type: "sprite",
texture: "enemy-texture",
width: 32,
height: 32,
});
// Añadir a la escena
scene.addEntity(enemy);
## Física (Box2D) — Fallback y configuración
El motor soporta integración opcional con Box2D (WASM) para física realista. En entornos donde Box2D no está disponible (por ejemplo en la ejecución de tests sin WASM), el sistema entra en modo "fallback" y las llamadas a la física no lanzan errores; en su lugar las operaciones se ignorarán o se comportarán de forma mínima.
Para habilitar Box2D y usar la implementación completa:
1. Instala el paquete WASM compatible, por ejemplo:
npm install box2d-wasm
2. Asegúrate de que tu bundler sirve y carga el binario WASM correctamente (Vite y bundlers modernos suelen manejar esto automáticamente si el paquete lo expone).
3. Inicializa el motor normalmente. Si Box2D se carga correctamente, el `PhysicsWorld` usará Box2D y activará colisiones, joints y efectos físicos reales.
Notas:
- Las pruebas y el entorno de CI pueden correr sin Box2D — el código está diseñado para fallar de forma segura.
- Si usas una variante diferente de Box2D (distintos empaquetados), algunas API o nombres de métodos pueden diferir; el motor aplica comprobaciones defensivas para soportar varias formas de binding, pero preferimos la práctica de usar `box2d-wasm` para compatibilidad máxima.
import { AssetManager } from "atomic-game-engine2d/assets/AssetManager";
// En tu función initialize()
const assetManager = AssetManager.getInstance();
await assetManager.loadTexture("player", "assets/player.png");
// Usar en un componente sprite
entity.addComponent({
type: "sprite",
texture: "player",
width: 48,
height: 48,
});
Explora nuestros ejemplos para aprender diferentes aspectos del motor:
Tu primer contacto con el motor. Aprende:
Un juego completo de disparos espaciales que muestra:
Un juego de plataformas con:
Clásico juego que incluye:
Juego de memoria que demuestra:
# Clonar el repositorio
git clone https://github.com/lemur-bookstores/atomic-game-engine2d.git
# Instalar dependencias
cd atomic-game-engine2d
npm install
# Construir el proyecto
npm run build
# Iniciar servidor de desarrollo
npm run dev
# Abrir navegador en http://localhost:5173/examples/
# Instalación de dependencias
npm install
# Desarrollo
npm run dev
# Construcción
npm run build
# Tests
npm run test
# Verificación de tipos
npm run type-check
# Linting
npm run lint
La documentación detallada del motor ahora está organizada por componente y sistema en la carpeta docs/. Cada entrada incluye una descripción y ejemplos de uso en TypeScript.
Principales documentos:
docs/ecs.md — Arquitectura ECS: Entidades, Componentes y Sistemas.docs/scene.md — Gestión de escenas y ciclo de vida.docs/entity.md — API de Entity y manipulación de componentes.docs/transform.md — Componente transform y transformaciones.docs/sprite.md — Componente sprite y AssetManager usage.docs/physics.md — PhysicsSystem, Box2D fallback y configuración.docs/collider.md — Colisionadores y detección de colisiones.docs/render-system.md — Render system, batching y cámaras.docs/input-system.md — InputManager e InputSystem (keyboard/mouse/touch).docs/event-system.md — EventSystem y patrón de eventos.docs/asset-manager.md — Carga y uso de texturas y assets.docs/particle-system.md — Particle system, emitters y serialization.docs/light-system.md — Light system and layer resolver.docs/script-component.md — ScriptComponent y ScriptSystem.docs/animation-system.md — AnimationSystem and SpriteSheet usage.Revisa docs/ para ejemplos de código y casos de uso concretos.
| sprite | Imagen/textura | texture, width, height, tint |
| rectangle | Forma rectangular | width, height, color |
| physics | Propiedades físicas | velocity, acceleration, mass |
| collider | Detección de colisiones | width, height, isTrigger |
| Sistema | Función |
|---|---|
RenderSystem | Dibuja entidades en pantalla |
InputSystem | Procesa entrada del usuario |
MovementSystem | Actualiza posiciones basado en física |
CollisionSystem | Detecta y procesa colisiones |
// Eventos del motor
ENGINE_EVENTS.INITIALIZED; // Motor inicializado
ENGINE_EVENTS.STARTED; // Motor iniciado
ENGINE_EVENTS.PAUSED; // Motor pausado
// Eventos de input
INPUT_EVENTS.KEYDOWN; // Tecla presionada
INPUT_EVENTS.KEYUP; // Tecla liberada
INPUT_EVENTS.MOUSEDOWN; // Click del mouse
INPUT_EVENTS.MOUSEMOVE; // Movimiento del mouse
// Eventos de física
PHYSICS_EVENTS.COLLISION_BEGIN; // Inicio de colisión
Para más detalles, explora:
Principales cambios:
AssetManager y nuevos métodos SpriteSheet.fromFrames & adapter de engine.onEnter/onExit.entityCreated, keyDown).ANIMATION:FRAME.FRAME, COMPLETE).Las contribuciones son bienvenidas! Por favor, lee nuestras guías de contribución antes de enviar un PR.
Este proyecto está licenciado bajo la Licencia MIT - ver el archivo LICENSE para más detalles.
FAQs
A lightweight 2D game engine for web browsers with ECS architecture
We found that atomic-game-engine2d demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.

Security News
OpenSSF has issued a high-severity advisory warning open source developers of an active Slack-based campaign using impersonation to deliver malware.

Research
/Security News
Malicious packages published to npm, PyPI, Go Modules, crates.io, and Packagist impersonate developer tooling to fetch staged malware, steal credentials and wallets, and enable remote access.