Most efficient way to detect collision of two divs

故事扮演 提交于 2019-12-02 16:16:26

问题


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


来源:https://stackoverflow.com/questions/21994350/most-efficient-way-to-detect-collision-of-two-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!