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:

package
{
	import flash.display.MovieClip;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	
	public class BallCollision extends MovieClip
	{
		private var mcBallContainer:MovieClip;
		private var nNumBalls:Number = 15;
		
		private var nStageWidth:Number = 500;
		private var nStageHeight:Number = 400;
		
		public function BallCollision ( ) : void
		{
			mcBallContainer = new MovieClip ( ) ;
			mcBallContainer.x = mcBallContainer.y = 0;
			stage.addChild(mcBallContainer);
			
			this.addEventListener ( Event.ENTER_FRAME, enterFrameHandler );
			
			for ( var i = 0; i < nNumBalls; i++ )
			{
				var mcBall:Ball = new Ball ( Math.floor ( ( Math.random() * 12 ) - 4 ), Math.floor ( ( Math.random() * 12 ) - 4 ) );
				mcBall.x = Math.random() * nStageWidth;
				mcBall.y = Math.random() * nStageHeight;
				mcBallContainer.addChild ( mcBall );
			}
		}
		
		private function enterFrameHandler ( E:Event ) : void
		{
			for ( var i = 0; i < mcBallContainer.numChildren; i++ )
			{
				var mcBall1:* = mcBallContainer.getChildAt( i );
				
				for ( var j = i + 1; j < mcBallContainer.numChildren; j++ )
				{
					var mcBall2:* = mcBallContainer.getChildAt( j );
					
					var nDistX:Number = Math.abs ( mcBall1.x - mcBall2.x );
					var nDistY:Number = Math.abs ( mcBall1.y - mcBall2.y );
					var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
					
					if ( nDistance < 20 )
					{
						solveBalls ( mcBall1, mcBall2 );
					}
				}
			}
		}
		
		private function solveBalls ( MCBallA:MovieClip, MCBallB:MovieClip ) : void
		{
			var nX1:Number = MCBallA.x;
			var nY1:Number = MCBallA.y;
			var nDistX:Number = MCBallB.x - nX1;
			var nDistY:Number = MCBallB.y - nY1;
			
			var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
			var nRadiusA:Number = MCBallA.width/2;
			var nRadiusB:Number = MCBallB.width/2;
			//var nRadius:Number = 10;
			
			var nNormalX:Number = nDistX/nDistance;
			var nNormalY:Number = nDistY/nDistance;
			
			var nMidpointX:Number = ( nX1 + MCBallB.x )/2;
			var nMidpointY:Number = ( nY1 + MCBallB.y )/2;
			
			MCBallA.x = nMidpointX - nNormalX * nRadiusA;
			MCBallA.y = nMidpointY - nNormalY * nRadiusA;
			MCBallB.x = nMidpointX + nNormalX * nRadiusB;
			MCBallB.y = nMidpointY + nNormalY * nRadiusB;
			
			var nVector:Number = ( ( MCBallA.nSpeedX - MCBallB.nSpeedX ) * nNormalX )+ ( ( MCBallA.nSpeedY - MCBallB.nSpeedY ) * nNormalY );
			var nVelX:Number = nVector * nNormalX;
			var nVelY:Number = nVector * nNormalY;
			
			MCBallA.nSpeedX -= nVelX;
			MCBallA.nSpeedY -= nVelY;
			MCBallB.nSpeedX += nVelX;
			MCBallB.nSpeedY += nVelY;
		}
	}
}

And this is the one to manage balls

package
{
	import flash.events.Event;
	import flash.display.MovieClip;
	
	public class Ball extends MovieClip
	{
		public var nSpeedX:Number;
		public var nSpeedY:Number;
		
		private var nStageWidth:Number = 500;
		private var nStageHeight:Number = 400;
		
		public function Ball ( NSpeedX:Number, NSpeedY:Number ) : void
		{
			nSpeedX = NSpeedX;
			nSpeedY = NSpeedY;
			
			this.addEventListener ( Event.ENTER_FRAME, onEnterFrameHandler );
		}
		
		private function onEnterFrameHandler ( E:Event ) : void
		{
			this.x -= nSpeedX;
			this.y -= nSpeedY;
			
			if ( this.x >= nStageWidth - 10 )
			{
				this.x = nStageWidth - 10;
				nSpeedX *= -1;
			}
			else if ( this.x <= 10 )
			{
				this.x = 10;
				nSpeedX *= -1;
			}
			
			if ( this.y >= nStageHeight - 10 )
			{
				this.y = nStageHeight - 10;
				nSpeedY *= -1;
			}
			else if ( this.y <= 10 )
			{
				this.y = 10;
				nSpeedY *= -1;
			}
			
		}
	}
}

Enjoy the result

And download the source code

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers