我还是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>
我想知道我在做错什么计算。
答案 0 :(得分:0)
您的计算本身很好-问题是您甚至在开始间隔之前就一次计算两个球之间的距离。需要在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>