2017-06-06 90 views
0

我正在用GameObjects构建游戏。在我的游戏中,我将GameObjects从CollidableObject中分离出来。所有对象(GameObjects和CollidableGameObjects)都被推送到一个名为gameObjects的单个数组中。将数组和阵列过滤为不同类型的阵列

当涉及到碰撞检测我想过滤gameObjects数组,所以我只能循环CollidableObject类型的对象。我创建了这个下面的代码:

let temp : any = this.gameObjects.filter(g => g instanceof CollidableObject); 

//optional 
let collidables : Array<CollidableObject> = temp; 

for (let obj1 of collidables) { 
    for (let obj2 of collidables){ 
     if (obj1 != obj2) { 
      if(obj1.hasCollision(obj2)) {   
       obj1.onCollision(obj2); 
       this.gameOver(); 
      } 
     } 
    } 
} 

问题1:为什么不能直接过滤到CollidableObject的阵列?

问题2:有没有一种更简单的方法来过滤某种类型的数组?

+0

对于你的第一个问题[这个问题](https://github.com/Microsoft/TypeScript/issues/7657)可能是相关的。 – Saravana

回答

1

你可以这样做:

let temp = this.gameObjects.filter(g => g instanceof CollidableObject) as CollidableObject[]; 

或签名添加到阵列接口:

interface Array<T> { 
    filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[]; 
} 

然后:

let temp = this.gameObjects.filter<CollidableObject>(g => g instanceof CollidableObject); 

如果你使用一个模块系统(即你正在导入/导出),那么你需要增加全局模块:

declare global { 
    interface Array<T> { 
     filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[]; 
    } 
}