javascript - JS : How to check collision of a lot of elements?

标签 javascript jquery

我随机生成了 40 个具有随机位置的 img,但在某些情况下,其中一些 img 发生冲突。

所以我的问题是如何检查它们是否发生碰撞并在发生碰撞时给出新的位置?

我的代码如下,还有注释可以清楚地说明。

$( document ).ready(function() {
    var viewport = $(window).height();
    var pageHeight = $(document).height();
    var pageWidth = $(document).width();
    var x = 1;
    var y = 1;
    var itemsPerPage = Math.floor(pageHeight / viewport * 10);

    var imgsArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];

    //Generate random nr for picking one of the images
    function generateRandomForArray() {
        var num = Math.floor(Math.random() * 9);
        return num;
    }

    //Generate random nr for picking one of the left position (max is page width)
    function generateLeftRandom() {
        var num = Math.floor(Math.random() * pageWidth);
        return num;
    }

    //Generate random nr for picking one of the top position (max is page height)
    function generateTopRandom() {
        var num = Math.floor(Math.random() * pageHeight);
        return num;
    }

    //Generate random nr for parallax data-velocity value
    function generateVelocityRandom() {
        var num = Math.random() * (0.1 - -0.1) + -0.1;;
        return num;
    }

    showLetter();

    //Attach img tags with random img src to #toAttachElements container
    function showLetter() {
        var letter = imgsArray[generateRandomForArray()];

        $("#toAttachElements").append("<img class='parallax' data-velocity='" + generateVelocityRandom() + "' src='wp-content/themes/thenewtonstartertheme/img/bg-elements/" + letter + ".png'>");

        x++;

        if (x < itemsPerPage) {
            showLetter();
        } 
    }

    //Add random positions to previosly attached imgs
    $('#toAttachElements > img').each( function(){
        var left = generateLeftRandom();
        var top = generateTopRandom();

        $(this).css({"position":"absolute","z-index":"1","top": top + "px", "left": left + "px"});
    });

});

编辑!我最终想到的解决方案是,我将页面分成几行,每一行都可以有一个图片。代码如下。

$( document ).ready(function() {
    if ($(".to-attach-elements")[0]){
        var viewport = $(window).height();
        var pageHeight = $(document).height();
        var pageWidth = $(document).width();
        var x = 1;
        var y = 1;
        var itemsPerPage = Math.floor(pageHeight / viewport * 10);

        var topRows = Math.floor(pageHeight / itemsPerPage);

        var imgsArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];

        //Generate random nr for picking one of the images
        function generateRandomForArray() {
            var num = Math.floor(Math.random() * 9);
            return num;
        }

        //Generate random nr for picking one of the left position (max is page width)
        function generateLeftRandom() {
            var num = Math.floor(Math.random() * pageWidth);
            return num;
        }

        //Generate random nr for picking one of the top position (max is page height)
        function generateTopRandom() {
            var num = Math.floor(Math.random() * topRows);
            return num;
        }

        //Generate random nr for parallax data-velocity value
        function generateVelocityRandom() {
            var num = Math.random() * (0.1 - -0.1) + -0.1;;
            return num;
        }

        var top = generateTopRandom();

        showLetter();

        //Attach img tags with random img src to #toAttachElements container
        function showLetter() {
            var letter = imgsArray[generateRandomForArray()];

            $(".to-attach-elements").append("<img class='parallax' data-velocity='" + generateVelocityRandom() + "' src='wp-content/themes/thenewtonstartertheme/img/bg-elements/" + letter + ".png'>");

            x++;

            if (x < itemsPerPage) {
                showLetter();
            } 
        }

        //Add random positions to previosly attached imgs
        $('.to-attach-elements > img').each( function(){
            var left = generateLeftRandom();

            $(this).css({"position":"absolute","z-index":"1","top": top + "px", "left": left + "px"});

            top = top + topRows;
        });
    }
});

最佳答案

您首先需要为图像获取一个随机位置,然后将其与已添加到页面的所有图像的位置进行检查。如果位置相交,那么您需要生成一个新位置。

以下代码会将每个图像放置在随机位置,并确保没有交叉点。请注意,此代码假定每个图像具有相同的宽度和高度,即 32x32。

function pointInPoint(point1, point2) {
  return !(point1.left > point2.left + 32 || 
           point1.left + 32 < point2.left || 
           point1.top > point2.top + 32 ||
           point1.top + 32 < point2.top);
}

var images = $('#toAttachElements > img');
var current = 0;
var position = {};
var positions = [];
var i = 0;
// store all positions for the images
for(i = 0; i < images.length; i++) {
  positions[i] = $(images[i]).position();
}

loop:
do {
  // get a random position
  position = { left: generateLeftRandom(), top: generateTopRandom() };
  // check for intersections
  for(i = 0; i < images.length; i++) {
    if(pointInPoint(positions[i], position)) {
      continue loop;
    }
  }

  // we need to update the left and top value for this image in the positions array
  positions[current] = position;
  $(images[current]).css({position: "absolute", zIndex: 1, top: position.top + "px", left: position.left + "px"});
} while(++current < images.length);

如果您想使用不同的尺寸,可以将 pointInPoint 更改为使用矩形。然后您需要获取每个图像的宽度和高度并相应地修改参数。

关于javascript - JS : How to check collision of a lot of elements?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301469/

相关文章:

php - 如果输入设置为使用 PHP 检查,jQuery 应该调用一些函数

javascript - 使用 jquery 设置/更改值以下拉

javascript - 如何使用 oboe 迭代对象数组?

php - HTML通过JSON输出,通过ajax激活

javascript - 使 knockout "visible"使用 CSS "visibility"属性

javascript - 使用 Ajax 调用返回 JSON 文件的 Highcharts

jquery - 如何改变tinymce jquery框的大小?

javascript - 如何使用 JQuery 在模糊() 上调用此函数?

javascript - 如何在没有冲突的情况下为多个 div 容器归档相同的 jquery 操作

javascript - 添加附加链接到响应式导航