mreinstein / ecs

data oriented, functional entity component system
MIT License
86 stars 8 forks source link

chain functions possible? #46

Open Lightnet opened 19 hours ago

Lightnet commented 19 hours ago

Just thought a few days ago. To chain the entity without need to repeat or is not possible?

I did some searching and found this.

https://dev.to/sundarbadagala081/javascript-chaining-3h6g

Just thinking of the best way to handle it. By using the chaining it.

Just example

function addEntity(world) {
//...
// do something
// this.world = world
//  this.CUBE = ECS.addEntity(world)
//...
  return {
   addComponent(name,data){
     //do something
     // ECS.addComponent(this.world, this.CUBE, name, data);
   }
  }
}
const world = ECS.addWorld();
const CUBE = ECS.addEntity(world);
CUBE.addComponent('mesh', mesh);
mreinstein commented 15 hours ago

Interesting idea! Chaining is kind of hard for functional things because there's no concept of "this" to return.

You could probably write your own wrapper object though, and use that. The article you linked have some viable ways to generate chainable objects. Internally each of those functions could just call the ECS functions.

Something that looks really promising is Javascript's upcoming pipeline operator:

https://tc39.es/proposal-pipeline-operator/

It's only in stage 2, but maybe someday. :)

mreinstein commented 15 hours ago

I prefer data driven approaches. You could build your own factory, for example:

function makeEntity (world, data) {
    const m = ECS.addEntitiy(world)
    for (cont componentName in data)
        ECS.addComponent(world, m, componentName, ...data[componentName])
    return m
}

const monster = makeEntity(world, {
    aabb: { width: 12, height: 14, position: [ 32,  106 ] },
    health: { hitPoints: 3 },
    pathfinding: { maxDistance },
    monster: { },
})

Way shorter than any of those complex factory systems, and faster too. :)