In this tutorial we will create a game where the objective is to prevent other objects from colliding with your cursor. We won't use Flash's built-in `hitTestObject()`

methods; instead we will write our own collision detection routines.

**Republished Tutorial**

Every few weeks, we revisit some of our reader's favorite posts from throughout the history of the site. This tutorial was first published in February of 2011.

## Final Result Preview

Let's take a look at the final result we will be working towards:

## Step 1: Start Off

Create a new Flash file (ActionScript 3.0)

Set the stage dimensions to 500x500px and FPS to 32.

## Step 2: The Ball Class

This class will contain all data related to one ball. A ball has a `_mass`

, a` _radius`

, an `_xSpeed`

and a `_ySpeed`

. So we will make a property for each. In the constructor we pass the mass, the angle and the speed of the ball. Because the class will be linked to a display object we can retrieve the the radius of our ball by dividing the width of the display object by 2. The `_xSpeed`

and `_ySpeed`

can be calculated by using simple sine and cosine functions.

package { import flash.display.Stage import flash.display.Sprite import flash.events.Event public class Ball extends Sprite { private var _radius:Number = 0 private var _mass:Number = 0 private var _xSpeed:Number = 0 private var _ySpeed:Number = 0 public function Ball(mass:Number = 10.0, angle:Number = Math.PI, speed:Number = 10.0):void { this.mass = mass this._radius = this.width/2 this.xSpeed = speed*Math.sin(angle) this.ySpeed = speed*Math.cos(angle) } } }

For more information on these trigonometric Math.sin() and Math.cos() functions, see this Quick Tip.

## Step 3: Providing Getters and Setters

In our Ball class we provide getters and setters for our properties.

public function get radius():Number { return this._radius } public function set mass(mass:Number):void { this._mass = mass } public function get mass():Number { return this._mass } public function set xSpeed(xSpeed:Number):void { this._xSpeed = xSpeed } public function get xSpeed():Number { return this._xSpeed } public function set ySpeed(ySpeed:Number):void { this._ySpeed = ySpeed } public function get ySpeed():Number { return this._ySpeed }

## Step 4: Update Function

This function updates the x and y properties of our ball according to the `_xSpeed`

and `_ySpeed`

. We'll implement this function in our `Ball`

class.

public function update():void { this.x += _xSpeed this.y += _ySpeed }

## Step 5: The Completed Class

We'll finish up our `Ball`

class in this step.

package { import flash.display.Stage import flash.display.Sprite import flash.events.Event public class Ball extends Sprite { private var _radius:Number = 0 private var _mass:Number = 0 private var _xSpeed:Number = 0 private var _ySpeed:Number = 0 public function Ball(mass:Number = 10.0, angle:Number = Math.PI, speed:Number = 10.0):void { this.mass = mass this._radius = this.width/2 this.xSpeed = speed*Math.sin(angle) this.ySpeed = speed*Math.cos(angle) } public function get radius():Number { return this._radius } public function set mass(mass:Number):void { this._mass = mass } public function get mass():Number { return this._mass } public function set xSpeed(xSpeed:Number):void { this._xSpeed = xSpeed } public function get xSpeed():Number { return this._xSpeed } public function set ySpeed(ySpeed:Number):void { this._ySpeed = ySpeed } public function get ySpeed():Number { return this._ySpeed } public function update():void { this.x += _xSpeed this.y += _ySpeed } } }

## Step 6: Display Objects for our Ball Class

In the source-files I included a start FLA which contains all the library items you need. You can draw them yourself if you want, of course. Make sure your FLA has the following display objects:

*(Ed. note: that's a typo: "ennemyball" should say "enemyball".)*

## Step 7: Linking our Library Objects

The `Ball`

class we just created has to be linked to the `enemyball`

Sprite in the library.

The `playerball`

Sprite must have `Ball`

as base class and `PlayerBall`

as class.

The `score`

movie clip must have a `Score`

class.

## Step 8: The Application Class (Document Class)

The `Application`

class will contain all the game logic. We import all the classes we need. As you can see we'll be using TweenMax.

Next we define our field variables. The first field variable is the `ballPlayer`

.

Because the base class of our `playerball`

Sprite is `Ball`

we can store this Class in the `ballPlayer`

variable. This makes it easier later on to check for collisions between the `ballPlayer`

and the enemy balls.

The second field variable is an array which will contain all our enemy balls. The third variable is the timer that will be used to perform the main game loop. The fourth and last field is an instance of our `Score`

library object that will be used to display the elapsed game time. In the constructor we call the `init()`

function which I'll explain in the next step.

package { import flash.display.Sprite import flash.display.Graphics import flash.events.Event import flash.events.TimerEvent import flash.events.MouseEvent import flash.geom.Matrix import flash.utils.Timer import flash.ui.Mouse import com.greensock.TweenMax import com.greensock.easing.* public class Application extends Sprite { private var ballPlayer:Ball private var eballs:Array private var tmr:Timer private var score:Score public function Application():void { init() } } }

Don't forget to link the document class!.

## Step 9: The init() Function

Take a look at this code:

private function init():void { ballPlayer = new PlayerBall() eballs = new Array() tmr = new Timer(10) score = new Score() stage.align = "TL" stage.scaleMode = "noScale" Mouse.hide() setBackground() score.x = stage.stageWidth/2 score.y = stage.stageHeight/2 stage.addChild(score) stage.addEventListener(MouseEvent.MOUSE_MOVE, updatePlayerBall) stage.addChild(ballPlayer) tmr.addEventListener(TimerEvent.TIMER, updateTime) stage.addEventListener(MouseEvent.CLICK, startGame) }

In the first four lines we initialize our field variables.

Next we make sure our stage is aligned to the top left corner and does not scale.

We hide the mouse cursor. Our cursor will be replaced with the `playerball`

Sprite. Next we call the `setBackground`

function(explained in the next step).

We center our `score`

on the screen and add it to the display list. To update the position of `ballPlayer`

we attach a MouseEvent.MOUSE_MOVE event to the stage.

The `updatePlayerBall`

function (explained in step 11) will handle this MouseEvent. Next we add the `ballPlayer`

to the display list.

The timer will be used to display the game time. We attach a TimerEvent.TIMER listener to our timer, which will trigger the `updateTime()`

function (explained in Step 12) every 10 milliseconds.

Finally, we add a MouseEvent.CLICK to our stage. The `startGame`

function (explained in step 13) will then start our game.

## Step 10: setBackground() Function

This function adds a radial gradient background to the display list. To draw a gradient on a Sprite you must define the type of gradient, the colors you want to use, alpha values of the colors, the ratios (these define the distribution of the colors)and the spread method.

For more information, see this Quick Tip on gradients.

private function setBackground():void { var type:String = "radial" var colors:Array = [0xffffff,0xcccccc] var alphas:Array = [ 1, 1 ] var ratios:Array = [ 0, 255 ] var matr:Matrix = new Matrix() matr.createGradientBox(stage.stageWidth, stage.stageHeight, Math.PI / 2, 0, 0 ) //SpreadMethod will define how the gradient is spread. Note!!! Flash uses CONSTANTS to represent String literals var sprMethod:String = "pad" //Start the Gradietn and pass our variables to it var sprite:Sprite = new Sprite() //Save typing + increase performance through local reference to a Graphics object var g:Graphics = sprite.graphics g.beginGradientFill( type, colors, alphas, ratios, matr, sprMethod ) g.drawRect(0,0,stage.stageWidth,stage.stageHeight) stage.addChild(sprite) }

## Step 11: updatePlayerBall() Function

This function updates the position of `ballPlayer`

according to the position of your mouse.

private function updatePlayerBall(e:MouseEvent):void { ballPlayer.x = mouseX ballPlayer.y = mouseY }

## Step 12: updateTime() Function

We calculate the time in seconds and put it inside the textbox of our `score`

Sprite. Every 5000ms (five seconds) we add a new ball to the game.

private function updateTime(e:TimerEvent):void { score.txtScore.text = String(((tmr.currentCount*tmr.delay)/1000).toFixed(2)); if((tmr.currentCount*tmr.delay) % 5000 == 0) { addBall(); } }

## Step 13: startGame() Function

The game is started by clicking the stage. First we remove the listener for the stage click, so that we can't start the game serveral times. We add three balls to the game by calling the `addBall()`

function (explained in the next step) three times. We start our timer which will update our game time.

Finally we add an ENTER_FRAME event to our stage. The `gameLoop()`

function (explained in Step 15) will update the position of our enemy balls.

private function startGame(e:MouseEvent):void { stage.removeEventListener(MouseEvent.CLICK, startGame) addBall() addBall() addBall() tmr.start() stage.addEventListener(Event.ENTER_FRAME, gameLoop) }

## Step 14: addBall() Function

First we make a new instance of our `Ball`

class. We position the `ball`

randomly on the stage with an alpha of 0 and add it to the display list.

Next we tween the alpha back to 1. (I use TweenMax, it's included in the source files. You can also use the built-in Flash tween engine.) The second tween isn't really a tween. It just waits a second and the `onComplete`

function pushes the `ball`

into our `eballs`

array. This way the `gameLoop()`

function (explained in the next step) can handle the rest.

private function addBall():void { var ball:Ball = new Ball(10, Math.random()*Math.PI*2, 5) ball.x = Math.random()*stage.stageWidth ball.y = Math.random()*stage.stageHeight ball.alpha = 0 stage.addChild(ball) TweenMax.to(ball, 0.5, {alpha:1}) TweenMax.to(ball, 0, {delay: 1, onComplete:function():void{eballs.push(ball)}}) }

## Step 15: gameLoop() Function

Every frame will go through this function.

private function gameLoop(e:Event):void { for (var i:uint = 0; i < eballs.length; i++) { for (var j:uint = i + 1; j < eballs.length; j++) { if (collision(eballs[i], eballs[j])) { doCollision(eballs[i], eballs[j]) } } if(collision(eballs[i], ballPlayer)) { endOfGame() break } eballs[i].update() checkBounds(eballs[i]) } }

We start by iterating through all of our enemy balls.

The second for-loop checks for collisions between the enemy balls. The loop starts at 'i + 1'. This way we don't double check the collisions.

Next we check if the `ballPlayer`

hits the enemy ball. If so, the game is finished. Then we update the position of our enemy ball.

We make sure the balls stay in the game screen by calling the function `checkBounds()`

(explained later on).

## Step 16: collision() Function

This function checks whether any given pair of balls are colliding.

First we calculate the x distance and the y distance between the two balls. Using Pythagoras's Theorem (see the following diagram) we calculate the absolute distance between them. If the distance is less or equal to the sum of the the radii of the balls we have a collision.

private function collision(ball1:Ball, ball2:Ball):Boolean { var xDist:Number = ball1.x - ball2.x var yDist:Number = ball1.y - ball2.y var Dist:Number = Math.sqrt(xDist * xDist + yDist * yDist) return Dist <= ball1.radius + ball2.radius }

## Step 17: doCollision() Function

This function will calculate the new x- and y-speeds of the balls according to the speed and angle of the collision. Warning: math ;)

First we calculate the horizontal distance between the two balls and then the vertical distance between the balls. With these distances (and a little more trigonometry) we can calculate the angle between the balls (see diagram).

Next we calculate what I call the *magnitude* of each ball. (We have an xspeed vector and a yspeed vector; the magnitude is the vector sum of those.) Then we calculate the angle of each ball (similar to the previous angle calculation).

Next we rotate the new x- and y-speeds of each ball. What we are actually doing is rotating the coordinate system. By rotating our axes we have a 1D collision. (See the following diagram).

Newton says that the total amount of kinetic energy in a closed system is constant. Now we use these formulae:

`v1 = (u1*(m1-m2) + 2*m2*u2)/(m1+m2)`

`v2 = (u2*(m2-m1) + 2*m1*u1)/(m1+m2)`

where:

v1 = final xSpeedBall 1

v2 = final xSpeedBall 2

m1 = mass ball 1

m2 = mass ball 2

u1 = initial speed ball 1

u2 = initial speed ball 2

The y-speeds don't change as it is a 1D collision.

With these formulae we can calculate the `xSpeed`

and `ySpeed`

of each ball.

Now whe have the new x- and y-speeds in our rotated coordinate system. The last step is to convert everything back to a normal coordinate system. We use `Math.PI/2`

because the angle between `xSpeed`

and `ySpeed`

must always be 90 degrees (pi/2 radians).

private function doCollision(ball1:Ball, ball2:Ball):void { var xDist:Number = ball1.x - ball2.x var yDist:Number = ball1.y - ball2.y var collisionAngle:Number = Math.atan2(yDist, xDist) var magBall1:Number = Math.sqrt(ball1.xSpeed*ball1.xSpeed+ball1.ySpeed*ball1.ySpeed) var magBall2:Number = Math.sqrt(ball2.xSpeed*ball2.xSpeed+ball2.ySpeed*ball2.ySpeed) var angleBall1:Number = Math.atan2(ball1.ySpeed, ball1.xSpeed) var angleBall2:Number = Math.atan2(ball2.ySpeed, ball2.xSpeed) var xSpeedBall1:Number = magBall1 * Math.cos(angleBall1-collisionAngle) var ySpeedBall1:Number = magBall1 * Math.sin(angleBall1-collisionAngle) var xSpeedBall2:Number = magBall2 * Math.cos(angleBall2-collisionAngle) var ySpeedBall2:Number = magBall2 * Math.sin(angleBall2-collisionAngle) var finalxSpeedBall1:Number = ((ball1.mass-ball2.mass)*xSpeedBall1+(ball2.mass+ball2.mass)*xSpeedBall2)/(ball1.mass+ball2.mass) var finalxSpeedBall2:Number = ((ball1.mass+ball1.mass)*xSpeedBall1+(ball2.mass-ball1.mass)*xSpeedBall2)/(ball1.mass+ball2.mass) var finalySpeedBall1:Number = ySpeedBall1 var finalySpeedBall2:Number = ySpeedBall2 ball1.xSpeed = Math.cos(collisionAngle)*finalxSpeedBall1+Math.cos(collisionAngle+Math.PI/2)*finalySpeedBall1 ball1.ySpeed = Math.sin(collisionAngle)*finalxSpeedBall1+Math.sin(collisionAngle+Math.PI/2)*finalySpeedBall1 ball2.xSpeed = Math.cos(collisionAngle)*finalxSpeedBall2+Math.cos(collisionAngle+Math.PI/2)*finalySpeedBall2 ball2.ySpeed = Math.sin(collisionAngle)*finalxSpeedBall2+Math.sin(collisionAngle+Math.PI/2)*finalySpeedBall2 }

To find more information about elastic collisions take a look at hoomanr.com.

## Step 18: endOfGame() Function

This is run when the game ends.

private function endOfGame():void { tmr.stop() Mouse.show() stage.removeEventListener(MouseEvent.MOUSE_MOVE, updatePlayerBall) stage.removeEventListener(Event.ENTER_FRAME, gameLoop) while(eballs.length > 0) { TweenMax.to(eballs[0], 0.5, {scaleX:0, scaleY:0, ease:Bounce.easeOut}) eballs.splice(0,1) } TweenMax.to(ballPlayer, 0.5, {scaleX:0, scaleY:0, ease:Bounce.easeOut}) }

First off all we stop the timer. We show the mouse again. Next we remove both the MOUSE_MOVE and ENTER_FRAME event listeners. Finally we make all the balls on the stage invisible.

## Step 19: checkBounds() Function

This function makes sure the balls stay inside the game screen. So if the ball hits the upper or lower side, we reverse the `ySpeed`

. if the ball hits the left or the right side of the screen we reverse the `xSpeed`

. It uses similar logic to the ball collision detection function to check whether the edges of the ball hits an edge of the screen.

private function checkBounds(ball:Ball):void { if((ball.x + ball.radius) > stage.stageWidth) { ball.x = stage.stageWidth - ball.radius ball.xSpeed *= -1 } if((ball.x - ball.radius) < 0) { ball.x = 0 + ball.radius ball.xSpeed *= -1 } if((ball.y + ball.radius) > stage.stageHeight) { ball.y = stage.stageHeight - ball.radius ball.ySpeed *= - 1 } if((ball.y - ball.radius) < 0) { ball.y = 0 + ball.radius ball.ySpeed *= - 1 } }

## Step 20: The Complete Application Class

We have completed our Application class. We now have a working game!!!

package { import flash.display.Sprite; import flash.display.Graphics; import flash.events.Event; import flash.events.TimerEvent; import flash.events.MouseEvent; import flash.geom.Matrix; import flash.utils.Timer; import flash.ui.Mouse; import com.greensock.TweenMax; import com.greensock.easing.*; public class Application extends Sprite { private var ballPlayer:Ball; private var eballs:Array; private var tmr:Timer; private var score:Score; public function Application():void { init(); } private function init():void { ballPlayer = new PlayerBall(); eballs = new Array(); tmr = new Timer(10); score = new Score(); stage.align = "TL"; stage.scaleMode = "noScale"; Mouse.hide(); setBackground(); score.x = stage.stageWidth / 2; score.y = stage.stageHeight / 2; stage.addChild(score); stage.addEventListener(MouseEvent.MOUSE_MOVE, updatePlayerBall); stage.addChild(ballPlayer); tmr.addEventListener(TimerEvent.TIMER, updateTime); stage.addEventListener(MouseEvent.CLICK, startGame); } private function setBackground():void { var type:String = "radial"; var colors:Array = [0xffffff,0xcccccc]; var alphas:Array = [1,1]; var ratios:Array = [0,255]; var matr:Matrix = new Matrix(); matr.createGradientBox(stage.stageWidth, stage.stageHeight, Math.PI / 2, 0, 0 ); //SpreadMethod will define how the gradient is spread. Note!!! Flash uses CONSTANTS to represent String literals var sprMethod:String = "pad"; //Start the Gradietn and pass our variables to it var sprite:Sprite = new Sprite(); //Save typing + increase performance through local reference to a Graphics object var g:Graphics = sprite.graphics; g.beginGradientFill( type, colors, alphas, ratios, matr, sprMethod ); g.drawRect(0,0,stage.stageWidth,stage.stageHeight); stage.addChild(sprite); } private function updatePlayerBall(e:MouseEvent):void { ballPlayer.x = mouseX; ballPlayer.y = mouseY; } private function updateTime(e:TimerEvent):void { score.txtScore.text = String(((tmr.currentCount*tmr.delay)/1000).toFixed(2)); if ((tmr.currentCount*tmr.delay) % 5000 == 0) { addBall(); } } private function startGame(e:MouseEvent):void { stage.removeEventListener(MouseEvent.CLICK, startGame); addBall(); addBall(); addBall(); tmr.start(); stage.addEventListener(Event.ENTER_FRAME, gameLoop); } private function addBall():void { var ball:Ball = new Ball(10,Math.random() * Math.PI * 2,5); ball.x = Math.random() * stage.stageWidth; ball.y = Math.random() * stage.stageHeight; ball.alpha = 0; stage.addChild(ball); TweenMax.to(ball, 0.5, {alpha:1}); TweenMax.to(ball, 0, {delay: 1, onComplete:function():void{eballs.push(ball)}}); } private function gameLoop(e:Event):void { for (var i:uint = 0; i < eballs.length; i++) { for (var j:uint = i + 1; j < eballs.length; j++) { if (collision(eballs[i],eballs[j])) { doCollision(eballs[i], eballs[j]); } } if (collision(eballs[i],ballPlayer)) { endOfGame(); break; } eballs[i].update(); checkBounds(eballs[i]); } } private function collision(ball1:Ball, ball2:Ball):Boolean { var xDist:Number = ball1.x - ball2.x; var yDist:Number = ball1.y - ball2.y; var Dist:Number = Math.sqrt(xDist * xDist + yDist * yDist); if (Dist <= ball1.radius + ball2.radius) { if (ball1.x < ball2.x) { ball1.x -= 2; ball2.x += 2; } else { ball1.x += 2; ball2.x -= 2; } if (ball1.y < ball2.y) { ball1.y -= 2; ball2.y += 2; } else { ball1.y += 2; ball2.y -= 2; } } return Dist <= ball1.radius + ball2.radius; } private function doCollision(ball1:Ball, ball2:Ball):void { var xDist:Number = ball1.x - ball2.x; var yDist:Number = ball1.y - ball2.y; var collisionAngle:Number = Math.atan2(yDist,xDist); var magBall1:Number = Math.sqrt(ball1.xSpeed * ball1.xSpeed + ball1.ySpeed * ball1.ySpeed); var magBall2:Number = Math.sqrt(ball2.xSpeed * ball2.xSpeed + ball2.ySpeed * ball2.ySpeed); var angleBall1:Number = Math.atan2(ball1.ySpeed,ball1.xSpeed); var angleBall2:Number = Math.atan2(ball2.ySpeed,ball2.xSpeed); var xSpeedBall1:Number = magBall1 * Math.cos(angleBall1 - collisionAngle); var ySpeedBall1:Number = magBall1 * Math.sin(angleBall1 - collisionAngle); var xSpeedBall2:Number = magBall2 * Math.cos(angleBall2 - collisionAngle); var ySpeedBall2:Number = magBall2 * Math.sin(angleBall2 - collisionAngle); var finalxSpeedBall1:Number = ((ball1.mass-ball2.mass)*xSpeedBall1+(ball2.mass+ball2.mass)*xSpeedBall2)/(ball1.mass+ball2.mass); var finalxSpeedBall2:Number = ((ball1.mass+ball1.mass)*xSpeedBall1+(ball2.mass-ball1.mass)*xSpeedBall2)/(ball1.mass+ball2.mass); var finalySpeedBall1:Number = ySpeedBall1; var finalySpeedBall2:Number = ySpeedBall2; ball1.xSpeed = Math.cos(collisionAngle) * finalxSpeedBall1 + Math.cos(collisionAngle + Math.PI / 2) * finalySpeedBall1; ball1.ySpeed = Math.sin(collisionAngle) * finalxSpeedBall1 + Math.sin(collisionAngle + Math.PI / 2) * finalySpeedBall1; ball2.xSpeed = Math.cos(collisionAngle) * finalxSpeedBall2 + Math.cos(collisionAngle + Math.PI / 2) * finalySpeedBall2; ball2.ySpeed = Math.sin(collisionAngle) * finalxSpeedBall2 + Math.sin(collisionAngle + Math.PI / 2) * finalySpeedBall2; } private function endOfGame():void { tmr.stop(); Mouse.show(); stage.removeEventListener(MouseEvent.MOUSE_MOVE, updatePlayerBall); stage.removeEventListener(Event.ENTER_FRAME, gameLoop); while (eballs.length > 0) { TweenMax.to(eballs[0], 0.5, {scaleX:0, scaleY:0, ease:Bounce.easeOut}); eballs.splice(0,1); } TweenMax.to(ballPlayer, 0.5, {scaleX:0, scaleY:0, ease:Bounce.easeOut}); } private function checkBounds(ball:Ball):void { if ((ball.x + ball.radius) > stage.stageWidth) { ball.x = stage.stageWidth - ball.radius; ball.xSpeed *= -1; } if ((ball.x - ball.radius) < 0) { ball.x = 0 + ball.radius; ball.xSpeed *= -1; } if ((ball.y + ball.radius) > stage.stageHeight) { ball.y = stage.stageHeight - ball.radius; ball.ySpeed *= -1; } if ((ball.y - ball.radius) < 0) { ball.y = 0 + ball.radius; ball.ySpeed *= -1; } } } }

## Conclusion

That's it for this tutorial. Of course you could add the possibility to restart the game, but that shouldn't be too hard. This basic example of elastic collisions can be used for bigger games like a billiards game or similar.

I hope you liked this tutorial, thanks for reading!