YVND
YVND

Reputation: 379

Error undefined object (whereas it was defined)

I'm currently making a top down shooter HTML5 game using canvas (JavaScript), here is my problem:

When I shoot, a function check if there is a collision with an enemy or not, if yes, it destroy the enemy and the bullet, BUT sometimes (randomly) the game chashes and returns an error:

uncaught TypeError: Cannot read property 'x' of undefined
at collides (game.js:274)
at checkBulletHits (game.js:177)
at Game (game.js:346)

In this error "undefined" is the last bullet I shoot, but this time the bullet is undefined for a reason I don't understand.

Here is the code involved:

var bullets = [];
var enemies = [];

function checkBulletHits() {
    if (bullets.length > 0 && enemies.length > 0) {
        for (j = bullets.length - 1; j >= 0; j--) {
            for (k = enemies.length - 1; k >= 0; k--) {
                if (collides(enemies[k], bullets[j])) {
                    enemies.splice(k, 1);
                    bullets.splice(j, 1);
                    player.points += 10;    
                }
            }
        }
    }
}

function collides(a, b) {
    return  a.x < b.x + b.w &&
        a.x + a.w > b.x &&
        a.y < b.y + b.h &&
        a.y + a.h > b.y;
}

checkBulletHits();

Full code here: https://pastebin.com/H2Cw1g5j

Upvotes: 0

Views: 64

Answers (1)

Cerbrus
Cerbrus

Reputation: 72849

When you have a collision, you remove the bullet at index j. Then the loop continues to the next enemy, and there's another check for the bullet at index j.

That bullet no longer exists, so you're calling collides(enemy, undefined).
Then, in collides, this will obviously throw an error: undefined.x.

Break out of the loop when you have a hit. Add a return statement at the end of the if block.

Upvotes: 2

Related Questions