JavaScript Circle在Collision上消失了

时间:2018-05-09 02:02:20

标签: javascript graphics 2d

进行一些2D JavaScript物理模拟。现在正在研究圆圈以进行圆周碰撞。问题是每当两个圆碰撞时,其中一个消失,另一个碰撞正确。我认为这可能与我如何更新和检测碰撞有关。

这是我的功能

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);
}

1 个答案:

答案 0 :(得分:0)

通常在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);

参见cirles [i] .mass [an]?这将导致未完成,然后导致NaN。

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