我在这个碰撞检测中做错了什么?

What am i doing wrong in this collision detection?

我还是初学者 JavaScript ,我花了一晚上阅读关于两个圆圈之间的碰撞检测,然后想出了以下内容。

你用这个公式求出球的距离:

Math.sqrt(Math.pow(x - x2, 2) + Math.pow(y - y2, 2));

那么你如果半径之和大于或等于距离,圆圈就会发生碰撞,我试图在我的代码中做到这一点,但它似乎对我不起作用。有人可以告诉我我做错了什么吗?

var canvas = document.getElementById("canv");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var x2 = canvas.width / 2;
var y = canvas.height - 20;
var y2 = 20;
var ballRadius = 20;
var ballRadius2 = 20;
var dx = 2;
var dy = -2;
var dx2 = 2;
var dy2 = 2;
var distance = Math.sqrt(Math.pow(x - x2, 2) + Math.pow(y - y2, 2));

function drawBall() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
  ctx.fillStyle = "green";
  ctx.fill();
  ctx.closePath();
}

function drawBall2() {
  ctx.beginPath();
  ctx.arc(x2, y2, ballRadius2, 0, Math.PI * 2);
  ctx.fillStyle = "blue";
  ctx.fill();
  ctx.closePath();
}

function draw() {
  drawBall();
  drawBall2();
  x += dx;
  y += dy;
  x2 += dx2;
  y2 += dy2
  if (x && x2 > canvas.width - ballRadius || x && x2 < ballRadius) {
    dx = -dx;
    dx2 = -dx2;
  }
  if (y && y2 > canvas.height - ballRadius || y && y2 < 0) {
    dy = -dy;
    dy2 = -dy2;
  }
  if (ballRadius + ballRadius2 >= distance) {
    alert("collision");
  }

}
setInterval(draw, 10);
<canvas id="canv" width="512" height="512"></canvas>

我想知道我在计算上做错了什么。

您的计算本身没有问题 - 问题是您甚至在开始间隔之前就计算了两个球之间的距离一次。需要在 setinterval 的回调函数中连续 重新计算距离。否则你只是在与一个固定数字进行比较——这是启动时两个球之间的距离。

这是一个例子:

var canvas = document.getElementById("canv");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var x2 = canvas.width / 2;
var y = canvas.height - 20;
var y2 = 20;
var ballRadius = 20;
var ballRadius2 = 20;
var dx = 2;
var dy = -2;
var dx2 = 2;
var dy2 = 2;
var distance = Math.sqrt(Math.pow(x - x2, 2) + Math.pow(y - y2, 2));

function drawBall() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
  ctx.fillStyle = "green";
  ctx.fill();
  ctx.closePath();
}

function drawBall2() {
  ctx.beginPath();
  ctx.arc(x2, y2, ballRadius2, 0, Math.PI * 2);
  ctx.fillStyle = "blue";
  ctx.fill();
  ctx.closePath();
}

function draw() {
  drawBall();
  drawBall2();
  x += dx;
  y += dy;
  x2 += dx2;
  y2 += dy2
  if (x && x2 > canvas.width - ballRadius || x && x2 < ballRadius) {
    dx = -dx;
    dx2 = -dx2;
  }
  if (y && y2 > canvas.height - ballRadius || y && y2 < 0) {
    dy = -dy;
    dy2 = -dy2;
  }
  distance = Math.sqrt(Math.pow(x - x2, 2) + Math.pow(y - y2, 2));
  if (ballRadius + ballRadius2 >= distance) {
    console.log("collision");
  }

}
setInterval(draw, 50);
<canvas id="canv"></canvas>