Search code examples
javascriptparticle-system

Javascript: Simple Particle Motion, Particle Elastically Bouncing Off Other Particle


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?


Solution

  • You are only comparing a molecule with 2 other ones, which in fact might be anywhere.
    Collision detection is a topic quite hard to solve, but if you want to have your idea working quickly you might go for a n^2 algorithm with 2 nested for loops.

    the code is quite expected :

      // 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;  // .
             }
      }
    

    the fiddle is here : http://jsbin.com/arokuz/10