JS Game - 无法设置undefined typeerror的属性

问题描述 投票:1回答:1

我知道有类似的问题,但它们不适用于我的情况,我不能浪费更多的时间。

我正在学习JS所以我正在尝试编写一个简单的pacman游戏。在这种情况下,每当pacman吃掉电源时,所有活跃的鬼魂都必须变成弱鬼。

问题出现的时候,我正在玩游戏时,我抓住了一个电源,游戏崩溃说:

Uncaught TypeError: Cannot set property 'isWeak' of undefined.

我没有在这个问题中发布所有代码。只有错误来自的主要部分(我想是这样)。

我在main.js中的代码:

var activeGhosts = [];
var powerups = [];
for (var i = 0; i < powerups.length; i++) {
    if (pacman.collision(powerups[i])) {
        makeWeak();
        powerups.splice(i,1);
    }

}
function makeWeak() {
    for (var i = 0; i < activeGhosts.length; i++) activeGhosts[i].isWeak = true;
}

我在ghost.js中的代码:

function Ghost(x,y,img){
this.x = x;
this.y = y;
this.img = img;
this.direction = 0;
this.radius = 16; // half of 32 px because every image is 32x32 px
this.crash = false;
this.isWeak = false;

this.show = function () {
    if (this.isWeak) {
        image(weakghostimg, this.x, this.y);
    } else {
        // img can be the all the different ghosts
        image(img, this.x, this.y);
    }
};
javascript undefined pacman
1个回答
0
投票

我有一个23x22列的平台,有不同的符号。如果我检测到“重新”,则表示我必须在该位置创建一个红色幽灵。

var ghosts = []; // array to draw them
var activeGhosts = []; // array to keep them alive and moving around   

for (var i = 0; i < plat.rows; i++) {
    for (var j = 0; j < plat.columns; j++) {
    if (plat.platform[i][j] === 're') ghosts.push(new Ghost(j * 32, i * 32, redGhostimg)); 

这是我用来将ghost插入activeGhosts数组的函数。为了开始幽灵的移动,每2秒我将一个幽灵移动到另一个阵列中。

function ghostsEscape() {
if (ghosts.length > 0) {
    var tempGhost = ghosts.pop();
    tempGhost.escape(plat);
    activeGhosts.push(tempGhost);
} else if (ghosts.length === 0) return;
setTimeout(ghostsEscape, 2000);

}

© www.soinside.com 2019 - 2024. All rights reserved.