我正在制作一款平台游戏,我想知道在使用数组检查冲突时,是否有一种更简单的方法可以将对象存储在数组中。类是否可以自动拥有任何类型的数组?
//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
}
对于一个类拥有的许多变量,是否有某种内置数组,这样我就可以快速检查碰撞,而不必为每个障碍调用addToArray函数?
您可以始终推送到构造函数中的数组
作业完成:p
可选,但我建议:使用类static
来保存阵列
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);
另一个有趣的选择可能是使用Set而不是数组
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);
});