jquery .animate() collision detection

拟墨画扇 提交于 2019-12-06 05:40:35
Randy Burden

Here's a simple implementation of jQuery animation and collision: http://jsfiddle.net/itechnology/XKJKD/

A similar question is posted here: jQuery collision detection during animation which references a jQuery collision plugin which looks promising: http://sourceforge.net/projects/jquerycollision/

I was faced with the same issue you are having, but I have decided to make my own solution. I wrote a plugin to bind a function call to collisions.

Live Demo: http://jsfiddle.net/lilglower/mptp3/5/

Here is the function:

$.fn.collide = function($selector, $callback){
    exists = 'collide' in $;
    if(!exists) $.collide = [];
    $.collide.push({
        s1 : $(this),
        s2 : $($selector),
        callback : $callback
    });
    if(!$.collideStarted){
        $.collideStarted = true;
        setInterval(function(){
            $.each($.collide, function(id, data){
                data.s1.each(function(){
                    $s1 = $(this);
                    data.s2.each(function(){
                        $s2 = $(this);
                        position1 = $s1.position();
                        position2 = $s2.position();
                        size1 = {width : $s1.width(), height : $s1.height()};
                        size2 = {width : $s2.width(), height : $s2.height()};
                        if (((position1.left + size1.width) > position2.left) &&
                        ((position1.top + size1.height) > position2.top) &&
                        ((position2.left + size2.width) > position1.left) &&
                        ((position2.top + size2.height) > position1.top))
                        {
                            data.callback($s1, $s2);
                        }
                    })
                })
            })
        }, 50);
    }
}

Here is an example of the usage:

$(function(){
    $(".left").animate($(".right").position());
    $(".left").collide(".right", function($left, $right){
         alert('collide!');
    })

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