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