Question

I am currently making a Space Invaders remake in JavaScript, and my animating and such has been going pretty great, up until now.

You see I have a Object called Alien that holds a single aliens data. Every time an Alien is created it is added to an array of aliens, name aliens, respectively. I also have a Object called a Shot, which holds the info on a Shot from the player. Shot calls a setInterval method on itself, which allows it to update and automagically move up the screen. I figure the best place to do collision detection calls would be in here, as I'll have access to the variables that are relevant.

JavaScript does not seem to like it though. For example I have this code as my auto-updating animation:

this.draw = function(shot){
    board.fillStyle = "black";
    board.fillRect(shot.x - 1, shot.y + 1, shot.img.width+2,shot.img.height+2);
    shot.y -= 1; 
    if(shot.y < -5){
        clearInterval(shot.shooting);
    }
    board.drawImage(shot.img, shot.x, shot.y); 

    if(isCollidingWithAlien(shot)){
        //Do Collision Detectiony Stuffs
    }
};

The code near the end though, if(isCollidingWithAlien(shot))... never seems to be run, as I've tested many times with different console.log statements.

Do you know why it isn't being run/how to fix this behaviour?

Here is the isCollidingWithAlien code:

var isCollidingWithAlien = function(shot){
    for(var i = 0; i < aliens; i++){
        return intersects(
            shot.x, 
            shot.y, 
            shot.img.width, 
            shot.img.height, 
            aliens[i].x, 
            aliens[i].y, 
            document.getElementById("alien").width, 
            document.getElementById("alien").height);
    }
};   

And here is the Collision Detection code:

// returns true if there is any overlap
// params: x,y,w,h of two rectangles
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
    w2 += x2;
    w1 += x1;
    if (x2 > w1 || x1 > w2) 
        return false;
    h2 += y2;
    h1 += y1;
    if (y2 > h1 || y1 > h2) 
        return false;
    return true;
}

Here is a JSFiddle to see it all in action: JSFiddle Link

Was it helpful?

Solution

You have a broken for statement.

Replace aliens with aliens.length

for (var i = 0; i < aliens.length; i++) {
        console.log("isCollidingWithAlien");
        return intersects(
        shot.x,
        shot.y,
        shot.img.width,
        shot.img.height,
        aliens[i].x,
        aliens[i].y,
        document.getElementById("alien").width,
        document.getElementById("alien").height);
}

I verified that the console is being logged to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top