我有4个这样的图像阵列:
car_image_left = new Image();
car_image_left.src = 'img/car2_left.png';
car_image_mid_left = new Image();
car_image_mid_left.src = 'img/car2_mid_left.png';
car_image_mid_right = new Image();
car_image_mid_right.src = 'img/car2_mid_right.png';
car_image_right = new Image();
car_image_right.src = 'img/car2_right.png';
car_image = [car_image_left,car_image_mid_left,car_image_mid_right,car_image_right];
他们都在这个阵列中:
images = [car_image, truck_image, hole_image, banana_image];
我的绘图功能出现问题:
for (i = 0; i < obstacles.length; i++){
this.context.drawImage(obstacles[i].images[obstacles[i].id][obstacles[i].lane-1],
obstacles[i].pos_x - obstacles[i].width/2,
obstacles[i].pos_y - obstacles[i].height/2,
obstacles[i].width,
obstacles[i].height);
}
所以,基本上Obstacles是一个存储我所有对象的数组,但它们都是不同的,除了每个对象都有一个ID。
这是一个类的例子:
function Car(lane) {
this.id = 0;
this.lane = lane;
this.height = 108.75;
this.width = 99;
this.pos_x = CENTER;
this.pos_y = -350;
this.car_image = images[this.id][this.lane-1];
}
答案 0 :(得分:1)
索引超出范围你得到未定义,我认为这就是行:
this.car_image = images[this.id][this.lane-1];
作为一个解决方案,将这个放在第一行之前,你应该明白到底出了什么问题:
console.log(images.length);
console.log(this.id);
console.log(images[this.id]);
console.log(images[this.id].length);
console.log(this.lane-1);
通过面对长度和指数,您应该看到哪个超出范围。