1

I've created this rather simple javascript; balls or 'molecules' moving around the screen. I was hoping to add to the functionality that when one ball comes into contact with another, they swap velocities. We don't need to worry about any angles, just when they come into contact with each other, the velocities swap. (Instead of changing the velocities though, in the code linked I've just coded a colour change)

I've been trying to call the function 'someplace' to recognise when the molecules touch, but I've had no luck with that. I don't really understand why.

Link to code:

http://jsbin.com/arokuz/5/

There seems to be three main problems:

  • The molecules seem to be randomly changing, rather than when two molecules touch.

  • When one sets the array to have say, 3 molecules, only two appear, the first is actually there, but unresponsive to .fillstyle changes, so invisible against the canvas

  • With the function method I would only be able to recognise when molecules in series (1 and 2 or 4 and 5) in the array touch...how could I check all the molecules?

4

2 回答 2

1

您只是将一个分子与另外两个分子进行比较,实际上可能在任何地方。
碰撞检测是一个很难解决的话题,但如果你想让你的想法快速发挥作用,你可能会选择一个带有 2 个嵌套 for 循环的 ^2 算法。

该代码是相当预期的:

  // collision
  for(var t = 0; t < molecules.length-1; t++)
     for(var tt = t+1; tt < molecules.length; tt++) {
         var p1 = molecules[t];
         var p2 = molecules[tt];
         if (sq(p1.x-p2.x) +sq(p1.y-p2.y) < sq(p1.radius+p2.radius) ) 
          {
            p1.collided = 8;  // will diplay for next 8 frames
            p2.collided = 8;  // .
         }
  }

小提琴在这里:http: //jsbin.com/arokuz/10

于 2013-08-06T23:19:14.747 回答
0

制作三个时只出现两个的原因不是因为第一个没有渲染,而是最后一个没有,这是因为您如何通过将其距离与列表中的下一个进行比较来绘制它们 -因为它是最后一个,所以没有下一个,因此抛出一个空错误并继续(检查控制台)。

他们似乎“随机”检测碰撞的原因是因为他们没有检查所有其他分子 - 只检查列表中的下一个,不幸的是,唯一简单的方法是为每个球检查所有其他球和检查。

为了让分子检测距离,您可以使用勾股定理,我通常使用它,例如:

var distx = Math.abs(molecule1.x - molecule2.x);
var disty = Math.abs(molecule1.x - molecule2.y);
var mindist = molecule1.radius + molecule2.radius;
return Math.sqrt(distx*distx+disty*disty) < mindist;
于 2013-08-06T22:27:25.040 回答