如何使用 jquery 检查两个 html 元素之间的碰撞

How to check for a collision between two html elements using jquery

我一直在开发一个基于文本的游戏,并且我 运行 遇到了创建一个检查两个元素之间碰撞的函数的问题;一个用箭头键移动的球,和一个管子(想想飞扬的小鸟)。经过相当多的研究和我自己的一些实验后,我仍然无法让它工作。

这是我当前的函数:

function collision(div1, div2) {
    var ballX = div1.offset().left;
    var ballY = div1.offset().top;
    var ballHeight = div1.outerHeight(true);
    var ballWidth = div1.outerWidth(true);
    var fullBallHeight = ballY + ballHeight;
    var fullBallWidth = ballX + ballWidth;
    var pipeX = div2.offset().left;
    var pipeY = div2.offset().top;
    var pipeHeight = div2.outerHeight(true);
    var pipeWidth = div2.outerWidth(true);
    var fullPipeHeight = pipeY + pipeHeight;
    var fullPipeWidth = pipeX + pipeWidth;

    if (fullBallHeight < pipeY || ballY > fullPipeHeight || fullBallWidth < pipeX || ballX > fullPipeWidth) {
      return true;
    }
    return false;
  }

并调用函数:

  if (collision($("#ball"), $(".pipe")) == true) {
    //code for game over
  } else if (collision($("#ball"), $(".pipe")) == false) {
    //calling loop function for ball animation
    loop();
  }

感谢所有意见,此时我会尝试几乎所有的方法。谢谢

要发生 2D 碰撞,需要同时发生 4 件事(所以它是 ,而不是):

  • 球的底部必须低于管的顶部 (fullBallHeight > pipeY)
  • 球的顶部必须高于管的底部 (ballY < fullPipeHeight)
  • 球的右边必须在管道左边的右边 (fullBallWidth > pipeX)
  • 球的左边必须在管道右边的左边 (ballX < fullPipeWidth)

(图片来自http://jonathanwhiting.com/tutorial/collision/,推荐阅读)

所以这是结果条件:

if (fullBallHeight > pipeY && ballY < fullPipeHeight && fullBallWidth > pipeX && ballX < fullPipeWidth) {