Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Last active September 16, 2022 21:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save TheSeamau5/292d104f0d8b21e45c3a to your computer and use it in GitHub Desktop.
Save TheSeamau5/292d104f0d8b21e45c3a to your computer and use it in GitHub Desktop.
ECS Example in Javascript / ES6
// 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