首页 > 解决方案 > 图片无法预加载 - 导致 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)){....

本质上,我试图在任何游戏逻辑运行之前加载图像,以避免这些未定义和类型错误。任何帮助表示赞赏。

标签: javascript

解决方案


推荐阅读