Last active
September 16, 2022 21:41
-
-
Save TheSeamau5/292d104f0d8b21e45c3a to your computer and use it in GitHub Desktop.
ECS Example in Javascript / ES6
This file contains hidden or 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
// HELPER FUNCTIONS | |
const has = (entity, components) => { | |
const exists = (x) => typeof x !== "undefined"; | |
return components.map((component) => exists(entity[component])) | |
.reduce((x,y) => x && y); | |
}; | |
const clone = (object) => { | |
if (object === null || typeof object !== 'object'){ | |
return object; | |
} | |
let temp = object.constructor(); | |
for (let property in object){ | |
temp[property] = clone(object[property]); | |
} | |
return temp; | |
}; | |
const compose = (f,g) =>{ | |
return (x) => f(g(x)); | |
}; | |
// ACTUAL CODE: | |
const mario = { | |
position : { x : 0, y : 0 }, | |
velocity : { x : 0, y : 0 }, | |
life : true, | |
mass : 20, | |
controllability : true, | |
groundedness : true | |
}; | |
const goomba = { | |
position : { x : 20, y : 0 }, | |
velocity : { x : -1, y : 0 }, | |
life : true, | |
mass : 10, | |
groundedness : true | |
}; | |
const lakituCloud = { | |
position : { x : 0, y : 0}, | |
velocity : { x : -2, y : 0}, | |
life : true, | |
flying : true | |
}; | |
const block = { | |
position : { x : 0, y : 0}, | |
destructability : true | |
}; | |
const move = (entity) => { | |
if (has(entity, ["position", "velocity"])){ | |
let outputEntity = clone(entity); | |
outputEntity.position.x += entity.velocity.x; | |
outputEntity.position.y += entity.velocity.y; | |
return outputEntity; | |
}else{ | |
return entity; | |
} | |
}; | |
const applyGravity = (force) => { | |
return (entity) => { | |
if (has(entity, ["mass", "velocity"])){ | |
let outputEntity = clone(entity); | |
outputEntity.velocity.x += force.x / entity.mass; | |
outputEntity.velocity.y += force.y / entity.mass; | |
return outputEntity; | |
}else{ | |
return entity; | |
} | |
}; | |
}; | |
const update = compose(move, applyGravity({x : 0, y : -9.81})); | |
const entities = [mario, goomba, lakituCloud, block]; | |
const updatedEntities = entities.map(update); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment