简体   繁体   English

JavaScript碰撞检测似乎不起作用?

[英]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. 而且我的意思是,我从来没有得到有效的打击或true回报。 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. 碰撞检测是针对玩家向异形船发射的子弹,只是为了澄清,如果重要的话: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 此外,如果你想查看所有代码,这里是一个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. @Update:一直在玩代码,它似乎正确地注册了第一个Alien创建的,如果你看看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: 如果你对某些外星人都是真的,你应该返回true,或者在所有外星人没有碰撞后返回false:

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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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