Question

http://designedbychristian.com/designedbychristian/u-vs-them/

That is what I am working on. You can use your arrow keys to move and space bar to shoot. And I am testing in Chrome.

I am trying to do collision detection with the bullet hitting the zombies(red divs)

setInterval(function(){
   var z = $(".zombie");
   var zoff = z.offset();
   var zleft = zoff.left;

   var b = $("#bullet");
   var boff = b.offset();
   var bleft = boff.left;
      if (localStorage.getItem('facing') == "right") {
          if (bleft >= zleft) {
              $("#zombie").remove()
              $("#bullet").remove()
            }  
            }else if (localStorage.getItem('facing') == "left") {
                if (bleft <= zleft) {
                $("#zombie").remove()
                $("#bullet").remove()
            }
      }

      },1);

My problem is that the bullet is taking out the zombies in the order of the thier spawning

Was it helpful?

Solution

That's because the selector using # will just take the first element with that ID. What you need to do is use a selector that finds all the zombies and checks if each one has been hit, then remove that one, instead of just checking the first one.

Use var z = $(".zombie"); to select all elements with the class zombie (as opposed to those with that ID) then look at this to figure out the rest: https://api.jquery.com/jQuery.each/

If you're still having problems I can try to post more code for you, but give it a go first ;) The game's looking pretty cool so far.

Edit: Ok, so looked at your updated code and what's going wrong is that you're using each to select and remove all of the zombies after trying to compare the whole list with the bullet. This code will remove all of the zombies no matter what:

$('.zombie').each(function () {
    $(this).remove()
})

What you really need to be doing is select all of the zombies, then use each to loop through the list of zombies and compare each one to the bullet once, and only delete it if there is a collision. Something like this should work as the contents of your setInterval, though you may need to tweak it a little:

var b = $("#bullet");
var boff = b.offset();
var bleft = boff.left;
$('.zombie').each(function () {
    var z = $(this);
    var zoff = z.offset();
    var zleft = zoff.left;

    if (localStorage.getItem('facing') == "right") {
        if (bleft >= zleft) {
            z.remove()
            b.remove()
            score++
        }
    } else if (localStorage.getItem('facing') == "left") {
        if (bleft <= zleft) {
            z.remove()
            b.remove()
            score++
        }
    }
}

Also, to optimise this, you might want to make a check at the beginning of the loop to see if the bullet has already hit a zombie - if so, the loop won't need to continue and run the rest of the code. I'll leave this up to you though.

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