Create a Flash ball game using AS3

Read all posts about "" game

Ok… I think it’s time to start talking about Actionscript 3. Even if AS2 is way to be dead, is becoming a bit obsolete… every new library like Box2DFlashAS3 only works in AS3, so sooner or later we must learn AS3.

Obviously I won’t stop talking about AS2 until it’s dead and stinking… but this tutorial is dedicated to AS3

I am going to create the same prototype explained at Flash game creation tutorial – part 1, just using AS3

The first thing you have to do, is creating the ball itself as a new object, and giving it the ball linkage name, as usual.

Then, in the Movie Properties panel, you must specify the document class. Also, in the Publish Settings panel, you must specify the path where you will save the class (called ClassPath) as shown in the image.

AS3

Now, you’re ready to write your class file… click on the pencil next to your document class name and here it is the AS3 code:

package {
	import flash.display.*;
	import flash.events.*;
	import flash.ui.*;
	public class as3ball extends MovieClip {
		var the_hero: Sprite = new ball();
		var power = 0.3;
		var friction = 0.95;
		var xspeed = 0;
		var yspeed = 0;
		var up = false;
		var down = false;
		var left = false;
		var right = false;
		public function as3ball() {
			addChild(the_hero);
			the_hero.x = 250;
			the_hero.y = 200;
			stage.addEventListener(KeyboardEvent.KEY_DOWN, key_pressed);
			stage.addEventListener(KeyboardEvent.KEY_UP, key_released);
			addEventListener(Event.ENTER_FRAME, render);
		}
		function key_pressed(e:KeyboardEvent):void {
			switch (e.keyCode) {
				case Keyboard.UP :
					up = true;
					break;
				case Keyboard.DOWN :
					down = true;
					break;
				case Keyboard.LEFT :
					left = true;
					break;
				case Keyboard.RIGHT :
					right = true;
					break;
			}
		}
		function key_released(e:KeyboardEvent):void {
			switch (e.keyCode) {
				case Keyboard.UP :
					up = false;
					break;
				case Keyboard.DOWN :
					down = false;
					break;
				case Keyboard.LEFT :
					left = false;
					break;
				case Keyboard.RIGHT :
					right = false;
					break;
			}
		}
		private function render(e:Event):void {
			if (up) {
				yspeed -= power;
			}
			if (down) {
				yspeed += power;
			}
			if (left) {
				xspeed -= power;
			}
			if (right) {
				xspeed += power;
			}
			xspeed *= friction;
			yspeed *= friction;
			the_hero.x += xspeed;
			the_hero.y += yspeed;
		}
	}
}

Line 1: declaration of the package in which we are going to build our class. Normally the syntax would be package

Line 2: importing the package that contains the core classes that the Flash Player uses to build visual displays.

Line 3: importing the package containing the classes to manage events such as keyboard events, mouse events, and more

Line 4: importing the package that contains user interface classes, such as classes for interacting with the mouse and keyboard

Line 5: declaration of the main class. Class name must be the same as the name of the .as file

Line 6: declaring a new variable called the_hero as a Sprite type (think about the sprite as an AS2 movieclip), and assigning it the ball movieclip. From now on, we will refer to the_hero everytime we want to move the ball.

Lines 7-10: declaring speed, power and friction variables as seen in the AS2 tutorial

Lines 11-14: Declaring four boolean variables, one for each direction, and setting them to false. You will understand why I am doing this later in this tutorial

Line 15: Declaration of the main function. You know this is the main function because of its name… the same as the class. Naming the function this way will make it execute once the movie is loaded

Line 16: Adding the hero to stage. addChild is the AS3 method to see a display object appear on the Stage. In this case, it displays the the_hero sprite that contains the ball movieclip

Lines 17-18: Placing the_hero movieclip in the centre of the stage.

Line 19: Adding a listener for the KEY_DOWN event (a key is pressed) and calling the key_pressed function when the event is triggered

Event listeners, which are also called event handlers, are functions that Flash Player executes in response to specific events. In this case, the specific event is “a key is pressed”, and the function to be executed is key_pressed. This function will be executed every time a key is pressed.

Line 20: Adding a listener for the KEY_UP event (a key is released) and calling the key_released function when the event is triggered

Line 21: Adding a listener for the ENTER_FRAME event (the beginning of a new frame, just like the old AS2 onEnterFrame) and calling the render function when the event is triggered

Line 23: Beginning of the function to be executed every time a key is pressed

Lines 24-37: Performing a switch with the keycode of the key pressed, setting to true the boolean variable corresponding to the arrow key pressed

Lines 39-53: Same thing for the key_pressed function, but the key_released sets to false the variable corresponding to the arrow key released

These two functions may seem useless, but they are the core of the script because I can’t perform the old Key.isDown… I can only see when a key is pressed and when a key is released. And remember the player can press more than a key at the same time

Line 55: Function to be executed at every frame

Lines 56-71 follow the same rules seen at Flash game creation tutorial – part 1.

And here’s the result:

As you can see, AS3 learning curve is a bit harder than AS2 one, but once you understand the basics, you can achieve results that are simply impossible to get with AS2

Hope this first tutorial will make you start using AS3 just like a lot of you said Flash game creation tutorial – part 1 made you start using AS2

Download the source code and give me feedback

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