Search code examples
javascriptjquerycollision-detection

Collision with multiple elements (each function?)


i have a div ("#basket") which should catch many elements with the same class (".food")

function collision($div1, $div2) {
      var x1 = $div1.offset().left;
      var y1 = $div1.offset().top;
      var h1 = $div1.outerHeight(true);
      var w1 = $div1.outerWidth(true);
      var b1 = y1 + h1;
      var r1 = x1 + w1;
      var x2 = $div2.offset().left;
      var y2 = $div2.offset().top;
      var h2 = $div2.outerHeight(true);
      var w2 = $div2.outerWidth(true);
      var b2 = y2 + h2;
      var r2 = x2 + w2;
      if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;

      var value = Number(($div1).attr("data-value"));
      $("#counter").html(parseInt($("#counter").html()) + value);

      function getsmall() {
        $div1.remove();
        //$div1.stop().animate({width: "0px",height:"0px"}, 200, function(){});
      }
      getsmall();
}


   window.setInterval(function() {
        var basket = $('#basket');
        var food_1 = ('#food_1'); // classname .food
        var food_2 = ('#food_2'); // classname .food
        collision($(food_1), $(basket));
        collision($(food_2), $(basket));
    }, 200);

there will be more than 20 of the .food and i dont want to write that many of code if i'm using ids of each element.

the function works great with two unique elements (two ids), but not with one element with an id and more than 20 elements with only classnames.

how can the function collision be executed to the #basket and many elements with classname .food ?


Solution

  • You can use the each function, it loops through all the elements in the jQuery object:

    window.setInterval(function(){
        var basket = $('#basket');
        var food = $('.food');
        // Here comes the magic
        food.each(function(){
            collision($(this), $(basket));
        });
    }, 200);