Managing multiple balls collisions with Flash: AS3 version

Some days ago Sunil Changrani sent me a the script to manage multiple balls collisions with Flash, in AS2.

Now, it's time for Andrew Cook to give us the AS3 version.

Hi Emanuele,

I've been coming to your blog for over a year now. I am doing a new game with Ball vs. Ball collision and turn to your tutorials for help. I am programming my game in AS3, so I reprogrammed the tutorial in AS3. I thought you might want to check it out. There are three files. The main .fla, a document class, and a Ball class.

Thank you for starting your great blog that helps developers like me all the time. I really appreciate the way you give back to the development community. Keep it up!

This is the script to solve collisions:

ACTIONSCRIPT:
  1. package
  2. {
  3.     import flash.display.MovieClip;
  4.     import flash.display.Stage;
  5.     import flash.events.Event;
  6.     import flash.events.KeyboardEvent;
  7.    
  8.     public class BallCollision extends MovieClip
  9.     {
  10.         private var mcBallContainer:MovieClip;
  11.         private var nNumBalls:Number = 15;
  12.        
  13.         private var nStageWidth:Number = 500;
  14.         private var nStageHeight:Number = 400;
  15.        
  16.         public function BallCollision ( ) : void
  17.         {
  18.             mcBallContainer = new MovieClip ( ) ;
  19.             mcBallContainer.x = mcBallContainer.y = 0;
  20.             stage.addChild(mcBallContainer);
  21.            
  22.             this.addEventListener ( Event.ENTER_FRAME, enterFrameHandler );
  23.            
  24.             for ( var i = 0; i <nNumBalls; i++ )
  25.             {
  26.                 var mcBall:Ball = new Ball ( Math.floor ( ( Math.random() * 12 ) - 4 ), Math.floor ( ( Math.random() * 12 ) - 4 ) );
  27.                 mcBall.x = Math.random() * nStageWidth;
  28.                 mcBall.y = Math.random() * nStageHeight;
  29.                 mcBallContainer.addChild ( mcBall );
  30.             }
  31.         }
  32.        
  33.         private function enterFrameHandler ( E:Event ) : void
  34.         {
  35.             for ( var i = 0; i <mcBallContainer.numChildren; i++ )
  36.             {
  37.                 var mcBall1:* = mcBallContainer.getChildAt( i );
  38.                
  39.                 for ( var j = i + 1; j <mcBallContainer.numChildren; j++ )
  40.                 {
  41.                     var mcBall2:* = mcBallContainer.getChildAt( j );
  42.                    
  43.                     var nDistX:Number = Math.abs ( mcBall1.x - mcBall2.x );
  44.                     var nDistY:Number = Math.abs ( mcBall1.y - mcBall2.y );
  45.                     var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
  46.                    
  47.                     if ( nDistance <20 )
  48.                     {
  49.                         solveBalls ( mcBall1, mcBall2 );
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.        
  55.         private function solveBalls ( MCBallA:MovieClip, MCBallB:MovieClip ) : void
  56.         {
  57.             var nX1:Number = MCBallA.x;
  58.             var nY1:Number = MCBallA.y;
  59.             var nDistX:Number = MCBallB.x - nX1;
  60.             var nDistY:Number = MCBallB.y - nY1;
  61.            
  62.             var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
  63.             var nRadiusA:Number = MCBallA.width/2;
  64.             var nRadiusB:Number = MCBallB.width/2;
  65.             //var nRadius:Number = 10;
  66.            
  67.             var nNormalX:Number = nDistX/nDistance;
  68.             var nNormalY:Number = nDistY/nDistance;
  69.            
  70.             var nMidpointX:Number = ( nX1 + MCBallB.x )/2;
  71.             var nMidpointY:Number = ( nY1 + MCBallB.y )/2;
  72.            
  73.             MCBallA.x = nMidpointX - nNormalX * nRadiusA;
  74.             MCBallA.y = nMidpointY - nNormalY * nRadiusA;
  75.             MCBallB.x = nMidpointX + nNormalX * nRadiusB;
  76.             MCBallB.y = nMidpointY + nNormalY * nRadiusB;
  77.            
  78.             var nVector:Number = ( ( MCBallA.nSpeedX - MCBallB.nSpeedX ) * nNormalX )+ ( ( MCBallA.nSpeedY - MCBallB.nSpeedY ) * nNormalY );
  79.             var nVelX:Number = nVector * nNormalX;
  80.             var nVelY:Number = nVector * nNormalY;
  81.            
  82.             MCBallA.nSpeedX -= nVelX;
  83.             MCBallA.nSpeedY -= nVelY;
  84.             MCBallB.nSpeedX += nVelX;
  85.             MCBallB.nSpeedY += nVelY;
  86.         }
  87.     }
  88. }

And this is the one to manage balls

ACTIONSCRIPT:
  1. package
  2. {
  3.     import flash.events.Event;
  4.     import flash.display.MovieClip;
  5.    
  6.     public class Ball extends MovieClip
  7.     {
  8.         public var nSpeedX:Number;
  9.         public var nSpeedY:Number;
  10.        
  11.         private var nStageWidth:Number = 500;
  12.         private var nStageHeight:Number = 400;
  13.        
  14.         public function Ball ( NSpeedX:Number, NSpeedY:Number ) : void
  15.         {
  16.             nSpeedX = NSpeedX;
  17.             nSpeedY = NSpeedY;
  18.            
  19.             this.addEventListener ( Event.ENTER_FRAME, onEnterFrameHandler );
  20.         }
  21.        
  22.         private function onEnterFrameHandler ( E:Event ) : void
  23.         {
  24.             this.x -= nSpeedX;
  25.             this.y -= nSpeedY;
  26.            
  27.             if ( this.x>= nStageWidth - 10 )
  28.             {
  29.                 this.x = nStageWidth - 10;
  30.                 nSpeedX *= -1;
  31.             }
  32.             else if ( this.x <= 10 )
  33.             {
  34.                 this.x = 10;
  35.                 nSpeedX *= -1;
  36.             }
  37.            
  38.             if ( this.y>= nStageHeight - 10 )
  39.             {
  40.                 this.y = nStageHeight - 10;
  41.                 nSpeedY *= -1;
  42.             }
  43.             else if ( this.y <= 10 )
  44.             {
  45.                 this.y = 10;
  46.                 nSpeedY *= -1;
  47.             }
  48.            
  49.         }
  50.     }
  51. }

Enjoy the result

And download the source code

Improve the blog rating this post
Tell me what do you think about this post. I'll write better and better entries.
1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 4.78 out of 5)
Loading ... Loading ...

» Flash Templates provided by Template Monster are pre-made web design products developed using Flash technology.
They can be easily customized to meet the unique requirements of your project.

16 Responses to “Managing multiple balls collisions with Flash: AS3 version”

  1. Jack Hopkins on June 8th, 2008 12:16 am

    How many balls can this handle before it lags?

    Nice post!

  2. CopyleftDev on June 8th, 2008 6:56 am

    I was able to get to a 1500 ball count before I saw a major chuck of lag. :) AS3 is no joke and it is only getting better :)

  3. Jack Hopkins on June 8th, 2008 11:58 am

    Thats quite a leap from the 300 we saw in AS2

    I have CS3 and I think I will take the leap to AS3
    after today!

  4. Kesh on June 9th, 2008 7:58 am

    How would u make an angle that the ball would hit? like a ball hitting an angled wall.

    |
    |
    O - - -/

  5. Kesh on June 9th, 2008 8:00 am

    okay the lines didnt work out well lol. lets try this again.

    …..|
    …..|
    …..|
    O—-/

    where the dashes are the balls old places.

  6. Robin on June 9th, 2008 9:26 am

    Balls are touching. Gay :P

  7. Scarybug on June 9th, 2008 5:06 pm

    change

    var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
    if ( nDistance <20 )
    {

    to

    var nDistanceSqr:Number = (nDistX * nDistX) + (nDistY * nDistY);
    if ( nDistanceSqr <400 )
    {

    for extra speed.

  8. Chris on June 9th, 2008 9:25 pm

    Additionally, There is no need to take the absolute value of nDistX and nDistY in these lines…

    var nDistX:Number = Math.abs ( mcBall1.x - mcBall2.x );
    var nDistY:Number = Math.abs ( mcBall1.y - mcBall2.y );

    Once you square them it doesn’t matter if they are negative or not. Shouldn’t be a huge boost but every little bit helps. Also, while we are optimizing there is no need really to declare nDistX and nDistY explicitly but I can see why it would be helpful for the tutorial.

  9. Mark on July 17th, 2008 5:32 am

    Great work!!

    Any thoughts on what happens if a ball has simultanious collisions from both sides?

    AKA Newtons cradle?

  10. Marc on July 18th, 2008 10:56 am

    Does anyone know how to add the functionality of being able to grab, hold and throw these balls? This is a great effort btw.

  11. bob on August 16th, 2008 7:08 pm

    does anyone know how the collisionBall cobject is created? i cant see it anywhere.

  12. bob on August 16th, 2008 10:00 pm

    u say 1500????
    it laggs with me with 300 balls
    150 balls is ok on my pc.

  13. Nathan on August 18th, 2008 10:44 pm

    Hey Emanuele,

    I’m just started using AS3. I’m creating a game where you drive a bumper car, there’s two variables, speed and rotate. Is there way you can make a realistic bounce off the walls. Thanx

  14. Nick on August 22nd, 2008 8:28 pm

    Andrew, this is great, *however* you have not commented your code, in particular your physics (use of the dot product etc.) so you are assuming everyone knows what this does. I ranked this 4 out of 5, it is otherwise a superbly well structured and relatively fast rehash on the bouncy ball theme.

  15. Joe on September 19th, 2008 3:53 pm

    yes some explanation of the physics would be greatly appreciated…
    anyone want to take a stab at it…
    maybe I’ll try.

Leave a Reply




Trackbacks

  1. Adobe Flash CS3- AS3 and AS2 game tutorials roundup | Lemlinh.com on August 19th, 2008 6:36 pm

    [...] Read more [...]