Most efficient way to detect collision of two divs

2020-05-04 11:46发布

问题:

I'm using Jquery Collision to detect two objects overlapping each other. Here is a JSFiddle of the problem. (apologies for including jquery collision script in HTML, couldn't find other way)

Click anywhere in the gray container to move the green div over the white div.

HTML Structure:

<div class="container">
    <div class="test"></div>
    <div class="menu"></div>
</div>

JS:

$(document).ready(function () {
    var hit_list;
    $(".container").click(function () {

        $(".menu").stop().animate({
            left: "+=100px"
        }, 300, function () {
            $(".menu").animate({
                left: "0"
            }, 800);
        });
        //Test for collision
        hit_list = $(".menu").collision(".test");
        if (hit_list.length != 0) {
            alert("welcome Earthling!");
        }
    });
});

The problem with my method is that, it doesn't detect collision every time. Even though it passes over the white division fine, the alert isn't displayed everytime.

Am I going wrong anywhere in checking for collision? Is there a better/more efficient method to detect collisions during animation ?

回答1:

jQuery animate has a step callback (https://api.jquery.com/animate/), it gets executed after each step of the animation.

Use it like this:

$(document).ready(function () {
    var hit_list;
    $(".container").click(function () {

        $(".menu").stop().animate({
            left: "+=100px"
        }, {
           duration: 300,
           complete: function () {
               $(".menu").animate({
                   left: "0"
               }, 800);
           },
           step: function(){
               //Test for collision
               hit_list = $(".menu").collision(".test");
               if (hit_list.length != 0) {
                   alert("welcome Earthling!");
               }
           }
         });
     });
 });


回答2:

Try this http://jsfiddle.net/aamir/y7PEp/6/

$(document).ready(function () {
    var hit_list;
    var hits=0;
    $(".container").click(function () {
        var $this = $(this);
        function checkCollision() {
           //Test for collision
            hit_list = $(".menu").collision(".test");
            if (hit_list.length != 0) {
                hits++;
                $(".menu").html(hits+ ' hits');
            } 
        }

        $(".menu").stop().animate({
            left: "100px"
        }, 300, function () {
            checkCollision();
            $(".menu").animate({
                left: "0"
            }, 800);
        });
    });
});