0

ctx与其他画布属性一起预定义。我不想用大量代码轰炸页面。

我正在构建一组文字对象,它们有一个方法。当我尝试调用该方法时,它说它未定义,如下所示:

var enemiesArray = [];

function createEnemy(ene) {
    for (e = 0; e <= ene; e++) {
        var t = Math.floor(Math.random() * 291)
        var p = Math.floor(Math.random() * 101)
        var enemies = {
            x: t,
            y: p,
            hp: 20,
            dir: 0,
            damageImage: function () {
                return "bomber4.png";
            }
        }
        enemiesArray.push(enemies);
    }
}
//an interval is set to call the following function:
function drawEnemey() {
    for (zdp in enemiesArray) {
        img = new Image();
        img.src = "Images/" + enemiesArray[zdp].damageImage(); //this is where I get the    error.
        img.style.width = "20px";
        ctx.drawImage(img, enemiesArray[zdp].x, enemiesArray[zdp].y);
        //move from side to side
        if (enemiesArray[zdp].dir == 0) {
            //move left
            enemiesArray[zdp].x -= 1;
            if (enemiesArray[zdp].x <= 0) enemiesArray[zdp].dir = 1;
        } else {
            //move right
            enemiesArray[zdp].x += 1;
            if (enemiesArray[zdp].x >= 290) enemiesArray[zdp].dir = 0;
        }
        //check if they are hit
    }
}

我不明白的是,当我按原样运行代码时,enemiesArray[zdp].x通过enemiesArray[zdp].dir定义,但enemiesArray[zdp].damageImage()不是。

4

0 回答 0