我仍然是 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/150
提交
取消