javascript - 图片无法预加载 - 导致 TypeErrors
问题描述
我正在制作一个香草 JS 飞扬小鸟游戏,但我得到了TypeError: Can't read property 'x' of undefined.
一个 pipeTop 变量。
在加载背景图像时,我猜在调用 pipeTop[i].x 之前管道图像不会加载。
我尝试预加载所有图像,并window.onload
为我的draw
函数包含一个,但在实现逻辑之前它似乎没有提供图像(或其属性)。
// draw images
window.onload = function draw() {
ctx.drawImage(bg,0,0);
for (var i = 0; i < pipe.length; i++){
ctx.drawImage(pipeTop, pipe[i].x, pipe[i].y);
ctx.drawImage(pipeBottom, pipe[i].x, pipe[i].y+constant);
pipe[i].x--;
if (pipe[i].x == 125){
pipe.push({
x : cvs.width,
y : Math.floor(Math.random()*pipeTop.height)-pipeTop.height
});
}
}
// Detect Collision
if (bX + bird.width >= pipe[i].x && bX <= pipe[i].x + pipeTop.width && (bY <= pipe[i].y + pipeTop.height || bY+bird.height >= pipe[i].y+constant || bY + bird.height >= cvs.height - fg.height)){
location.reload();
}
if (pipe[i].x == 5) {
score+= 5;
score.play();
}
我尝试的预加载(现在已注释掉)是:
// function preloadImage(url) {
// var img = new Image();
// img.src = url;
// }
// preloadImage(
// "images/pipeBottom.png",
// "images/pipeTop.png",
// "images/fg.png",
// "images/bg.png",
// "images/bird.png"
// )
具有 typeError 的行是:
if (bX + bird.width >= pipe[i].x && bX <= pipe[i].x + pipeTop.width && (bY <= pipe[i].y + pipeTop.height || bY+bird.height >= pipe[i].y+constant || bY + bird.height >= cvs.height - fg.height)){....
本质上,我试图在任何游戏逻辑运行之前加载图像,以避免这些未定义和类型错误。任何帮助表示赞赏。
解决方案
推荐阅读
- webpack - HtmlWebpackPlugin 抛出 TypeError:更新到 Webpack5 后无法读取未定义的属性“哈希”
- jquery - Jquery可编辑选择不适用于动态输入下拉元素
- extjs - 如何为 Sencha 2x 构建自定义 app.json?
- angular - Angular 订阅数据以显示在表单 UI 中
- python - 无法在单独的功能中使用光标
- android - 在 Android Studio 中加载哪些 API 级别?
- javascript - Sequelize – where with count
- tetgen - tetgen(3D 网格生成器):生成简单立方体网格的节点中的奇怪引用
- c++ - 错误:“value_type”没有在 C++ 中命名类型
- css - R Markdown中的标签集创建未定义的标签