简体   繁体   中英

Most efficient way to detect collision of two divs

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 ?

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!");
               }
           }
         });
     });
 });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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