NateTheGreatt / bitECS

Functional, minimal, data-oriented, ultra-high performance ECS library written in JavaScript
Mozilla Public License 2.0
927 stars 84 forks source link

How to push / pop from a list? #112

Open watch-janick opened 1 year ago

watch-janick commented 1 year ago

I'm trying to build a component to store effects that can be applied on any character, think of it as a buff / debuff in a RPG game. How would you manage to add / remove those buffs / debuffs? Component:

import { defineComponent, Types } from 'bitecs'

const Effect = defineComponent({
  effects: [Types.ui8],
})

export default Effect

System:

import { defineQuery } from 'bitecs'

const effectQuery = defineQuery([Effect])

const effectSystem = (world: IMyWorld) => {
  const entities = effectQuery(world)
  entities.forEach((entity) => {
    Effect.effects[entity].forEach((effect) => {
      // remove effect if some condition is met
    })

    // if some condition is met, add an effect)
    if (true) {
      const effectId = 12
      Effect.effects[entity].push(effectId)
    }
  })
}

Thanks!

NateTheGreatt commented 1 year ago

if you don't mind defining a max amount of effects you can do something like this:

const DynamicArrayComponent = defineComponent({
  someDynamicArray: {
    array: [f32, 12],
    cursor: ui8,
  }
})

const push = (darray, eid, value) => { darray.array[eid][darray.cursor[eid]++] = value }

push(DynamicArrayComponent.someDynamicArray, eid, 1)