Most efficient way to detect collision of two divs

前端 未结 2 1980
無奈伤痛
無奈伤痛 2021-01-27 12:23

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 HTM

相关标签:
2条回答
  • 2021-01-27 12:43

    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);
            });
        });
    });
    
    0 讨论(0)
  • 2021-01-27 12:45

    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!");
                   }
               }
             });
         });
     });
    
    0 讨论(0)
提交回复
热议问题