Last active
November 12, 2021 13:10
-
-
Save pcornier/e09bc94c5bfc09b03490cdd12b804fca to your computer and use it in GitHub Desktop.
A minimal Javascript game engine that has an ECS, a state manager and a global bus event system in 30 lines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Bus = () => { | |
let listeners = {} | |
return { | |
register: (event, cb) => { | |
listeners[event] = listeners[event] || [] | |
listeners[event].push(cb) | |
}, | |
emit: (event, ...payload) => { | |
listeners[event].forEach(cb => cb(...payload)) | |
} | |
} | |
} | |
const StateManager = () => new Proxy([], { | |
get(t, fn) { | |
const _fn = t[fn] | |
return function(...args) { | |
const state = args[0] || t[t.length-1] | |
if (state[fn]) state[fn]() | |
if (_fn) return _fn.apply(t, args) | |
return t | |
} | |
} | |
}) | |
const update = (systems, entites) => { | |
for (system of systems) | |
entites | |
.filter(e => system.components.every(p => p in e)) | |
.forEach(e => system.process(e)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let systems = [] | |
let entities = [] | |
let BUS = Bus() | |
BUS.register('deleteBall', e => { | |
entities.splice(entities.indexOf(e), 1) | |
console.log('removed a ball') | |
}) | |
BUS.register('createBall', args => { | |
entities.push({ position: {x: args[0], y: args[1]}, gravity: args[2] }) | |
console.log('just created a new ball') | |
}) | |
const sm = StateManager() | |
const game = { | |
push: () => { | |
fallingSystem = { | |
components: ['position', 'gravity'], | |
process: entity => { | |
entity.position.y += entity.gravity; | |
console.log(`ball new Y position is ${entity.position.y}`) | |
if (entity.position.y > 300) BUS.emit('deleteBall', entity) | |
} | |
} | |
renderingSystem = { | |
components: ['position'], | |
process: entity => console.log(`I'm at ${entity.position.y}`) | |
} | |
systems.push(fallingSystem) | |
BUS.emit('createBall', 10, 10, 1) | |
}, | |
update: () => update(systems, entities) | |
} | |
sm.push(game) | |
function mainLoop() { sm.update() } | |
setInterval(mainLoop, 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment