JavaScript Circle 在 Collision 上消失了



做一个2D JavaScript物理模拟。现在正在处理圆到圆的碰撞。问题是每当 2 个圆圈碰撞时,其中一个消失而另一个正确碰撞。我认为这可能与我如何更新和检测碰撞有关。

这是我的函数

function animate() {
c.fillStyle = "#000000";
c.fillRect(container.x, container.y, container.width, container.height);
var newVx1 = 0;
var newVy1 = 0;
//loop through the circles array
for (var i = 0; i < circles.length; i++) {
//draw the circles
c.fillStyle = "hsl(" + circles[i].color++ + ", 100%, 100%)";
c.beginPath();
c.arc(circles[i].x, circles[i].y, circles[i].r, 0, Math.PI * 2, true);
c.fill();
//check circle on circle collisions 
for (var an = 0; an < circles.length; an++) {
if (an != i) {
var a = circles[i].x - circles[an].x;
var b = circles[i].y - circles[an].y;
if (Math.sqrt(a * a + b * b) < circles[i].r + circles[an].r) {
var xHit =
circles[i].x * circles[an].r + circles[an].x * circles[i].r;
var yHit =
circles[i].y * circles[an].r + circles[an].y * circles[i].r;
newVx1 =
(circles[i].vx * (circles[i].mass - circles[an].mass) +
2 * circles[i].mass[an] * circles[i].vx) /
(circles[i].mass + circles[an].mass);
//var temp = 0
newVy1 =
(circles[i].vy * (circles[i].mass - circles[an].mass) +
2 * circles[an].mass * circles[an].vy) /
(circles[i].mass + circles[an].mass);
var newVx2 =
(circles[an].vx * (circles[an].mass - circles[i].mass) +
2 * circles[i].mass * circles[i].vx) /
(circles[i].mass + circles[an].mass);
var newVy2 =
(circles[an].vy * (circles[an].mass - circles[i].mass) +
2 * circles[i].mass * circles[i].vy) /
(circles[i].mass + circles[an].mass);
circles[i].vx = newVx1;
circles[an].vx = newVx2;
circles[i].vy = newVy1;
circles[an].vy =newVy2;
}
}
}

if (
circles[i].x - circles[i].r + circles[i].vx < container.x ||
circles[i].x + circles[i].r + circles[i].vx >
container.x + container.width
) {
circles[i].vx = circles[i].bounce * -circles[i].vx;
//circles[i].vx = -circles[i].vx;
}
if (
circles[i].y + circles[i].r + circles[i].vy >
container.y + container.height ||
circles[i].y - circles[i].r + circles[i].vy < container.y
) {
circles[i].vy = circles[i].bounce * -circles[i].vy;
// circles[i].vx = -circles[i].vx;
}
circles[i].x += circles[i].vx;
circles[i].y += circles[i].vy;
circles[i].vy += 0.06;
//wind factor
//circles[i].vx += .0001*circles[i].r
}


requestAnimationFrame(animate);
}

通常在 Canvas 中,当某些东西神奇地消失时,可能是因为您传递给 canvas 的数据不再有效。

如果你控制台.log圆圈数据进行调试,你会看到"x"和"vx"现在都是NaN。

继续回溯此错误,您会发现 NaN 源自这行代码,它有一个拼写错误。

newVx1 =
(circles[i].vx * (circles[i].mass - circles[an].mass) +
2 * circles[i].mass[an] * circles[i].vx) /
(circles[i].mass + circles[an].mass);

看到卷曲[i].mass[an]?这将导致一个不确定的,然后导致一个 NaN。

你的碰撞仍然表现得很奇怪,但至少现在它没有消失。例

相关内容

  • 没有找到相关文章