Skip to content

Duplicate components

Marc Flerackers edited this page Sep 22, 2024 · 2 revisions

Sometimes the lack of support for duplicate components encumbers the usability of the API. A physics example would be constraints. You need be able to attach more than one constraint to an object, but it won't let you do that if components need to be unique. Another example would be gear or abilities you want to attach to a character. A solution would be to support array components like

add([
  pos(10, 10),
  sprite("bean"),
  weapon("longsword"),
  gear("cursed ribbon"),
  gear("cheap boots"),
]);

Since gear would be an array property, the first gear would merge functions into the object to modify gear, like usual properties. The next gear component will just add gear to the current gear. Thus, obj.use(gear("poison dagger")) will add more gear rather than replacing all gear. The gear component could implement addGear/removeGear to add or remove specific gear. The addGear function would be located and called by use(). obj.unuse("gear") will remove the entire gear interface from the object.

function gear(gearId: string): GearComp {
  const _gear:string[] = [gearId];
  return {
    id: "gear",
    type: "array",
    gear: _gear,
    addGear(gear: string | GearComp) {
      if (gear instanceof GearComp) {
        _gear.push(gear.gear[0]);
      }
      else {
        _gear.push(gear);
      }
    },
    removeGear(gearId: string) {
      const index = _gear.indexOf(gearId);
      if (index >= 0) {
        _gear.splice(index, 1);
      }
    }
  }
}
Clone this wiki locally