Search code examples
javascriptarraysclassfor-loopcollision

Is there a class array?


I am making a platformer game and I am wondering if there is a simpler way to store objects in arrays as I use the arrays to check for collision. Is there any type of array a class can automatically have?

//This is with making my own array
var obstacleArray = [];
class Obstacle {
    constructor(x, y) {
        this.x = x,
        this.y = y,
        this.width = 50,
        this.height = 50
    }
    
    addToArray() {
        obstacleArray.push(this);
    }
}
obstacle1 = new Obstacle(0, 0);
obstacle2 = new Obstacle(50, 0);
obstacle1.addToArray();
obstacle2.addToArray();
for (let i = 0; i < obstacleArray.length;i++) {
    //check for collision
}

Is there some kind of built-in array for a number of variables a class owns so I can quickly check for collision without having to call the addToArray function for every obstacle?


Solution

  • You can always push to the array in the constructor

    Job done :p

    Optional but I recommend it: Use a class static to hold the array

    class Obstacle {
        static obstacleArray = [];
        constructor(x, y) {
            this.x = x;
            this.y = y;
            this.width = 50;
            this.height = 50;
            Obstacle.obstacleArray.push(this);
        }
    }
    obstacle1 = new Obstacle(0, 0);
    obstacle2 = new Obstacle(50, 0);
    console.log(Obstacle.obstacleArray);

    Another interesting option may be to use a Set instead of an array

    class Obstacle {
        static obstacles = new Set;
        constructor(x, y) {
            this.x = x;
            this.y = y;
            this.width = 50;
            this.height = 50;
            Obstacle.obstacles.add(this);
        }
        remove() {
            Obstacle.obstacles.delete(this);
        }
    }
    obstacle1 = new Obstacle(0, 0);
    obstacle2 = new Obstacle(50, 0);
    [...Obstacle.obstacles.keys()].forEach(obstacle => {
        console.log(obstacle.x);
    });
    // you can remove an obstacle easily
    console.log('removed 1');
    obstacle1.remove();
    [...Obstacle.obstacles.keys()].forEach(obstacle => {
        console.log(obstacle.x);
    });