Question

I am trying to check collision between 2 divs and it works only for first div. what might be the issue. My fiddle is here

$(document).ready(function () {
        $("#txt").keydown(function(pk){
            var pos = $('#myCar').position();

            if(pk.keyCode == '37')
            {
                $('#myCar').css('left', pos.left - 10 + 'px');
            }
            if(pk.keyCode == '38')
            {      
                $('#myCar').css('top', pos.top - 10 + 'px');
            }
            if(pk.keyCode == '39')
            {
                $('#myCar').css('left', pos.left + 30 + 'px');
            }
            if(pk.keyCode == '40')
            {
                $('#myCar').css('top', pos.top + 10 + 'px');
            }

        });
        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;
            return true;
        }

        //detect collision for every 2 seconds
        window.setInterval(function () {
            $('#result').text(collision($('#myCar'), $('.otherCar')));
        }, 200);

        });
Was it helpful?

Solution

The problem is that using the jQuery selector $('.otherCar') doesn't actually use all of the elements with that class in this case. When you try to get a specific value from a class selector like that, there is no way for it to return all of the values for each element, and work with your logic, so instead it just gives you one of them.

In this case, you will need to use jQuery's .each():

    //detect collision for every 2 seconds

    window.setInterval(function () {
        $('#result').text('False');
        $.each($('.otherCar'),function(){
            if(collision($('#myCar'), $(this))){
                $('#result').text('True');
            }
        });
    }, 200);

Basically, I use all the same code as you did, but I use .each() to loop through every item in that selector, and then run your collision() function for each one (using the $(this) selector to get the current element in the loop)

Before the loop, I reset the result text to say 'False', before continuing on to check the elements. If none are found to be true, this will remain as 'False', and be good to go.

I wrapped the function call in an if() statement, so if the function returns true, the conditional will evaluate to true, and change the result text to 'True'.

See Demo

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