Collisions Between Same-Mass Objects

Remember good old Chapter 11 and conservation of momentum? That was some pretty serious code. It happens you can make it a little bit simpler when two objects of the same mass collide. Basically, along the line of collision, such objects simply swap their velocities. While you still have coordinate rotation to determine that line of collision, as well as the objects velocities on it, this wipes out the complex conservation of momentum stuff. To see how it works, lets go back to file ch11_06.fla , which well use as the base for the next example, ch19_13.fla . Im not going to list all of the code from the original here, as its quite a big file. But lets take a look at the for loop that created all the balls:

 for(var i:Number = 0;i<numBalls;i++) {       var ball:MovieClip = attachMovie("ball", "ball" + i, i);       ball._x = Math.random() * Stage.width;       ball._y = Math.random() * Stage.height;       ball.vx = Math.random() * 10 - 5;       ball.vy = Math.random() * 10 - 5;  ball._xscale = ball._yscale = ball.mass = Math.random() * 250 + 20;  } 

For the new file, youll start by removing that last line, shown in bold. This will make all the balls the same size and remove the notion of mass, effectively giving them all the same mass.

Next you want to go down to the checkCollision function. Find the section that reads like this:

 // rotate ball0's velocity var vel0:Object = rotate(ball0.vx, ball0.vy, sine, cosine, true); // rotate ball1's velocity var vel1:Object = rotate(ball1.vx, ball1.vy, sine, cosine, true); // collision reaction var vxTotal:Number = vel0.x - vel1.x; vel0.x = ((ball0.mass - ball1.mass) *           vel0.x + 2 * ball1.mass * vel1.x) /          (ball0.mass + ball1.mass); vel1.x = vxTotal + vel0.x; 

This is the part that finds the velocities along the line of collision, and, along with their masses, figures out the result of the collision. The part labeled collision reaction is the part that factors in the conservation of momentum, and this is the part you can get rid of. You can replace that portion with code that simply swaps vel0 and vel1 . This makes the whole section just shown look like this:

 // rotate ball0's velocity var vel0:Object = rotate(ball0.vx, ball0.vy, sine, cosine, true); // rotate ball1's velocity var vel1:Object = rotate(ball1.vx, ball1.vy, sine, cosine, true);  // swap the two velocities   var temp:Object = vel0;   vel0 = vel1;   vel1 = temp;  

This could be even further optimized, but Ill leave it like this for claritys sake. Here youve gotten rid of a good bit of math, and if you test the file before and after, you should be seeing the same thing.



Foundation ActionScript. Animation. Making Things Move
Foundation Actionscript 3.0 Animation: Making Things Move!
ISBN: 1590597915
EAN: 2147483647
Year: 2005
Pages: 137
Authors: Keith Peters

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net