Skip to content

Instantly share code, notes, and snippets.

@pcornier
Last active November 12, 2021 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcornier/e09bc94c5bfc09b03490cdd12b804fca to your computer and use it in GitHub Desktop.
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
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))
}
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