简体   繁体   中英

JavaScript Collision Detection doesn't seem to be working?

So I'm trying to set-up Collision Detection in my rendition of Alien Invaders. But it hardly works. And by hardly I mean I've never gotten a valid hit, or true return. I've even tried a bunch of different methods, but for whatever reason I haven't been able to get a correct answer.

The Collision Detection is for the Players bullet firing to the Alien ships, just for clarification, if it matters :D.

Here is the Collision Detection code: (I tried to make it error prone, in hope for a hit, although no method seems to work)

var isCollidingWithAlien = function(shot){
    var alienImg = document.getElementById('alien');
    for(var i = 0; i < aliens.length; i++){
        return shot.x               < aliens[i].x + alienImg.width  && 
        shot.x + shot.img.width     > aliens[i].x                   &&
        shot.y                      < aliens[i].y + alienImg.height && 
        shot.y + shot.img.height    > aliens[i].y;
    }
};

It's not that the code isn't being called, or some strange technical error. It just never returns true.

Also if you want to view all code, here is a JSFiddle

@Update: Been playing with the code, and it seems to register correctly for the first Alien created, the one on the top left if you look at the JSFiddle. Not sure why though

the problem is, you return the collision ONLY for the first alien in the list. you should return true if you get true for some alien, or return false, after all aliens doesn't collide:

var isCollidingWithAlien = function(shot){
    var alienImg = document.getElementById('alien');
    for(var i = 0; i < aliens.length; i++){
        var result = shot.x         < aliens[i].x + alienImg.width  && 
        shot.x + shot.img.width     > aliens[i].x                   &&
        shot.y                      < aliens[i].y + alienImg.height && 
        shot.y + shot.img.height    > aliens[i].y;
        if(result)
            return true;
    }
    return false;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM