我如何检查两个div是否在javascript中互相触摸

时间:2019-04-28 14:06:36

标签: javascript jquery html5

我有一个从左到右运行的div。 和一个div上下波动。 我想检查一下它们是否彼此相交 (有点像游戏中的跳跃)。 我试图用console.log记录他们的每一点(从左上到右下), 但即使他们在同一地点,他们也只是不见面。 我有一个人给我的代码,如果他们相交就会做某事。 问题是它说“如果”始终为真。 如果我删除'!'根本不起作用

我的代码:

    $('#startBtn').click(function () {
    moveCars();
})

$('body').keydown(function (e) {
    if (e.key == 'ArrowUp') {
        $('#player').css('bottom', '+=140px');
    }

    if ($('#player').css('top') < '0') {
        $('#player').css('bottom', '25px');
    }
});

$('body').keydown(function (e) {

    if ($('#player').css('bottom') <= '20px') {
        if (e.key == 'ArrowDown') {
            $('#player').css('bottom', '20px');
        }
    } else {
        if (e.key == 'ArrowDown') {
            $('#player').css('bottom', '-=140px');
        }
    }
});

function moveCars() {

    $('.carLeft').css('display', 'inline');

    function moveCar() {
        $('.carRight').css('right', '-=2px');

        if ($('.carRight').css('right') <= '0%') {
            $('.carRight').css('right', '105%');
        }
    }

    setInterval(moveCar)

    function moveLeftCars() {
        $('.carLeft').css('left', '-=3px');

        if ($('.carLeft').css('left') <= '0%') {
            $('.carLeft').css('left', '90%');
        }
    }
    setInterval(moveLeftCars)

}


var carsRight = document.querySelector('.carRight');
var carsLeft = document.querySelector('.carLeft');
var player = document.querySelector('#player');

var carRightBound = carsRight.getBoundingClientRect();
var carLeftBound = carsLeft.getBoundingClientRect();
var playerBound = player.getBoundingClientRect();


setInterval(function(carRightBound, playerBound){



    if(!(carRightBound.left > playerBound.right || carRightBound.right < playerBound.left || carRightBound.top > playerBound.bottom || carRightBound.bottom < playerBound.top)) {
        console.log('The divs are intersecting!');
        alert('on here')
    } else {
        console.log('The divs are not intersecting.');
    }

},5000)

可以删除setInterval。

1 个答案:

答案 0 :(得分:0)

目前,您要在开始间隔之前将游戏对象的边界矩形分配给变量carRightBound和playerBound 一次。 这意味着它的值将永远不会更新。您应该在回调函数中更新它们。

此外,5000ms的间隔太长。在5秒钟内,屏幕上可能发生很多事情。例如,尝试将其减少到50ms。

最后我还是不太确定您的碰撞检测。您无需关注对象的大小。

尝试以下代码:

setInterval(function() {
  var playerBound = player.getBoundingClientRect();
  var carsRight = document.querySelectorAll('.carRight');
  var carRightBound;

  for (var a = 0; a < carsRight.length; a++) {
    carRightBound = carsRight[a].getBoundingClientRect();
    if (playerBound.x > carRightBound.x - playerBound.width && playerBound.x < carRightBound.x + carRightBound.width && playerBound.y > carRightBound.y - playerBound.height && playerBound.y < carRightBound.y + carRightBound.height) {
      console.log('The divs are intersecting!');
      alert('on here')
    } else {
      console.log('The divs are not intersecting.');
    }
  }
}, 50);