I'm building a game with GameObjects. In my game i have separated GameObjects from CollidableObject. All objects (GameObjects and CollidableGameObjects) are pushed to one single array called gameObjects.
When it comes to collision detection i wish to filter the gameObjects array so i can loop over only objects of type CollidableObject. I created the following code for this:
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();
}
}
}
}
Question 1: Why is it not possible to directly filter to an array of CollidableObject?
Question 2: Is there an easier way to filter the array on a certain type?
You can do this:
let temp = this.gameObjects.filter(g => g instanceof CollidableObject) as CollidableObject[];
Or add a signature to the array interface:
interface Array<T> {
filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[];
}
And then:
let temp = this.gameObjects.filter<CollidableObject>(g => g instanceof CollidableObject);
If you're using a module system (that is you are importing/exporting) then you need to augment the global module:
declare global {
interface Array<T> {
filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With