Javascript 使用JQuery检测两个旋转的div是否冲突

Javascript 使用JQuery检测两个旋转的div是否冲突,javascript,jquery,html,css,rotation,Javascript,Jquery,Html,Css,Rotation,我想检测两个旋转的div是否发生碰撞。如果它们没有旋转,我知道怎么做,但如果它们真的旋转,我不知道怎么做 我尝试了一些冲突插件,比如jQuery collision(),但是当div旋转时,它们就不起作用了 我使用CSS的transform属性对div进行了旋转。我通过yckart找到了它。 我在这里摆弄了一下旋转的div: 您可以自己更改CSS中div的旋转,检测仍然可以正常工作 重叠。js: (function ($) { $.fn.overlaps = function (obj)

我想检测两个旋转的div是否发生碰撞。如果它们没有旋转,我知道怎么做,但如果它们真的旋转,我不知道怎么做

我尝试了一些冲突插件,比如jQuery collision(),但是当div旋转时,它们就不起作用了

我使用CSS的transform属性对div进行了旋转。

我通过yckart找到了它。

我在这里摆弄了一下旋转的div:

您可以自己更改CSS中div的旋转,检测仍然可以正常工作

重叠。js

(function ($) {
    $.fn.overlaps = function (obj) {
        var elems = {
            targets: [],
            hits: []
        };
        this.each(function () {
            var bounds = $(this).offset();
            bounds.right = bounds.left + $(this).outerWidth();
            bounds.bottom = bounds.top + $(this).outerHeight();

            var compare = $(obj).offset();
            compare.right = compare.left + $(obj).outerWidth();
            compare.bottom = compare.top + $(obj).outerHeight();

            if (!(compare.right < bounds.left || compare.left > bounds.right || compare.bottom < bounds.top || compare.top > bounds.bottom)) {
                elems.targets.push(this);
                elems.hits.push(obj);
            }
        });

        return elems;
    };
}(jQuery));
(函数($){
$.fn.overlaps=功能(obj){
变量元素={
目标:[],
点击次数:[]
};
这个。每个(函数(){
变量边界=$(this.offset();
bounds.right=bounds.left+$(this).outerWidth();
bounds.bottom=bounds.top+$(this.outerHeight();
var compare=$(obj.offset();
compare.right=compare.left+$(obj).outerWidth();
compare.bottom=compare.top+$(obj.outerHeight();
if(!(compare.rightbounds.right | | compare.bottombounds.bottom)){
元素目标推(这个);
元素点击推送(obj);
}
});
返回元素;
};
}(jQuery));
希望我能帮上忙

编辑:


多亏了@jbrosi,overlaps.js在旋转div时并不能很好地工作。

您正在寻找div碰撞检测

如果你想引发一个事件,你必须反复测试,但是最好是在你所有的div上运行这个函数

示例演示位于

这是您需要使用的函数

function collision($div1, $div2) {
      var x1 = $div1.offset().left;
      var y1 = $div1.offset().top;
      var h1 = $div1.outerHeight(true);
      var w1 = $div1.outerWidth(true);
      var b1 = y1 + h1;
      var r1 = x1 + w1;
      var x2 = $div2.offset().left;
      var y2 = $div2.offset().top;
      var h2 = $div2.outerHeight(true);
      var w2 = $div2.outerWidth(true);
      var b2 = y2 + h2;
      var r2 = x2 + w2;

      if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
      return true;
    }
函数冲突($div1,$div2){
var x1=$div1.offset().left;
变量y1=$div1.offset().top;
var h1=$div1.outerHeight(true);
var w1=$div1.外径(真);
var b1=y1+h1;
var r1=x1+w1;
var x2=$div2.offset().left;
变量y2=$div2.offset().top;
var h2=$div2.outerHeight(真);
var w2=$div2.外径(真);
var b2=y2+h2;
var r2=x2+w2;
如果(b1b2 | r1r2)返回false;
返回true;
}
另一个演示

您还可以参考以了解collison检测

对于此用途,请参见以下代码:

var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();
var overlaps=(函数(){
函数getPositions(elem){
变量位置、宽度、高度;
pos=$(elem.position();
宽度=$(元素).width();
高度=$(elem).height();
返回[[pos.left,pos.left+宽度],[pos.top,pos.top+高度]];
}
功能比较位置(p1、p2){
变量r1,r2;
r1=p1[0]r2[0]| | r1[0]==r2[0];
}
返回函数(a,b){
var pos1=获取位置(a),
pos2=getPositions(b);
返回比较位置(pos1[0],pos2[0])&比较位置(pos1[1],pos2[1]);
};
})();

希望这能对您有所帮助:)

它不是100%准确,但在大多数情况下确实有效,我使用了以下算法:

函数未定义(a){
返回a==未定义;
}
/**
*用于确定所述两个多边形之间是否存在交点的辅助函数
*通过顶点列表。使用分离轴定理
*
*@param一组连接点[{x:,y:},{x:,y:},…]构成一个闭合多边形
*@param b一组连接点[{x:,y:},{x:,y:},…]构成一个闭合多边形
*@如果两个多边形之间存在任何交点,则返回true,否则返回false
*/
函数doPolygonsIntersect(a,b){
var多边形=[a,b];
var minA,maxA,projected,i,i1,j,minB,maxB;
对于(i=0;i最大值){
maxA=预测值;
}
}
//对于第二个形状中的每个顶点,将其投影到与边垂直的线上
//并跟踪这些值的最小值和最大值
minB=maxB=未定义;
对于(j=0;j最大值){
maxB=预测值;
}
}
//如果两个项目之间没有重叠,那么我们所看到的边缘将两者分开
//多边形,我们知道没有重叠
if(maxAfunction isUndefined(a) {
    return a === undefined;
}

/**
 * Helper function to determine whether there is an intersection between the two polygons described
 * by the lists of vertices. Uses the Separating Axis Theorem
 *
 * @param a an array of connected points [{x:, y:}, {x:, y:},...] that form a closed polygon
 * @param b an array of connected points [{x:, y:}, {x:, y:},...] that form a closed polygon
 * @return true if there is any intersection between the 2 polygons, false otherwise
 */
function doPolygonsIntersect (a, b) {
    var polygons = [a, b];
    var minA, maxA, projected, i, i1, j, minB, maxB;

    for (i = 0; i < polygons.length; i++) {

        // for each polygon, look at each edge of the polygon, and determine if it separates
        // the two shapes
        var polygon = polygons[i];
        for (i1 = 0; i1 < polygon.length; i1++) {

            // grab 2 vertices to create an edge
            var i2 = (i1 + 1) % polygon.length;
            var p1 = polygon[i1];
            var p2 = polygon[i2];

            // find the line perpendicular to this edge
            var normal = { x: p2.y - p1.y, y: p1.x - p2.x };

            minA = maxA = undefined;
            // for each vertex in the first shape, project it onto the line perpendicular to the edge
            // and keep track of the min and max of these values
            for (j = 0; j < a.length; j++) {
                projected = normal.x * a[j].x + normal.y * a[j].y;
                if (isUndefined(minA) || projected < minA) {
                    minA = projected;
                }
                if (isUndefined(maxA) || projected > maxA) {
                    maxA = projected;
                }
            }

            // for each vertex in the second shape, project it onto the line perpendicular to the edge
            // and keep track of the min and max of these values
            minB = maxB = undefined;
            for (j = 0; j < b.length; j++) {
                projected = normal.x * b[j].x + normal.y * b[j].y;
                if (isUndefined(minB) || projected < minB) {
                    minB = projected;
                }
                if (isUndefined(maxB) || projected > maxB) {
                    maxB = projected;
                }
            }

            // if there is no overlap between the projects, the edge we are looking at separates the two
            // polygons, and we know there is no overlap
            if (maxA < minB || maxB < minA) {
                console.log("polygons don't intersect!");
                return false;
            }
        }
    }
    return true;
};

$('#r').click(function() {
    var rota = Math.floor( Math.random() * 100 ),
        rotb = Math.floor( Math.random() * 100 ),
        pointsa = new Array(4),
        pointsb = new Array(4);

    $('#a').css('transform', 'rotateZ(' + rota + 'deg)');
    $('#b').css('transform', 'rotateZ(' + rotb + 'deg)');

    $('#a div').each(function(i) {
        pointsa[i] = {x: parseInt($(this).offset().left), y: parseInt($(this).offset().top)};
    });

    $('#b div').each(function(i) {
        pointsb[i] = {x: parseInt($(this).offset().left), y: parseInt($(this).offset().top)};
    });


    $('#s').val("intersection: " + doPolygonsIntersect(pointsb, pointsa).toString());
});