如何遍历两个具有共同属性的数组?

时间:2019-04-29 16:36:07

标签: javascript typescript data-oriented-design entity-component-system

我一直在前端使用Pixi.js在javascript中开发一个非常苗条的实体组件系统,我对大家有一个问题 一个常见的模式是您在系统中使用的迭代器,例如在Unity中,您可以执行以下操作:

    [ComponentType1, ComponentType2], 
    (c1: ComponentType1, c2: ComponentType2) => {
         // run ops on the components
     })

假设您有一个实体数组和两个包含那些组件类型的数组,需要调用一个函数并将这两个组件作为参数传递,那么您将如何构建forEach函数呢?本质上,迭代具有两种类型组件的实体的最优化方法是什么?

一种简便的方法似乎是遍历实体列表并检查其组件类型,但是我想知道是否有更好的方法。这种方法看起来像这样:

function forEach<T, K>(components: [c1: T, c2: K], callback: (c1: T, c2: K)=> void) {
    entities.forEach((entity) => { 

        if (entity.hasComponent(c1) && entity.hasComponent(c2)) {

            callback(entity.getComponent(c1), entity.getComponent(c2)

        }
}

0 个答案:

没有答案