Introduction to AS3 classes

In my opinion one of the most important reasons people are afraid to migrate from AS2 to AS3 is its way of scripting.

Pure AS3 coding dislikes coding on the timeline and wants us to write and use custom classes.

Don’t worry: you can still write your script on the timeline but you won’t be able to benefit of new AS3 features doing this way.

If you want to buy a Flash AS3 version and keep on writing on the timeline, then simply don’t buy it.

You will find it’s not that hard to learn AS3 classes, but one common mistake is keeping the entire code into a single class.

If you aren’t doing this for an educational purpose (it’s easier to explain the code when it’s all on a single file), then you should write as many classes as you can.

The reason is simple: the code is cleaner and easier to read.

Moreover once you wrote a messy class you won’t be able to use it again in a future project, but if you have a collection of small classes, there are good chances to use them again and again and again, saving a lot of time and work.

This is a “wrong” class that simply traces if I pressed up, down, left, right or space keys.

I’ve taken it from New tile based platform engine – AS3 version.

package {
	import flash.display.Sprite;
	import flash.ui.Mouse;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	public class all_in_one extends Sprite {
		var press_left = false;
		var press_right = false;
		var press_up = false;
		var press_down = false;
		var press_space = false;
		public function all_in_one() {
			addEventListener(Event.ENTER_FRAME,on_enter_frame);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, key_down);
			stage.addEventListener(KeyboardEvent.KEY_UP, key_up);
		}
		public function key_down(event:KeyboardEvent) {
			if (event.keyCode == 32) {
				press_space = true;
			}
			if (event.keyCode == 37) {
				press_left = true;
			}
			if (event.keyCode == 38) {
				press_up = true;
			}
			if (event.keyCode == 39) {
				press_right = true;
			}
			if (event.keyCode == 40) {
				press_down = true;
			}
		}
		public function key_up(event:KeyboardEvent) {
			if (event.keyCode == 32) {
				press_space = false;
			}
			if (event.keyCode == 37) {
				press_left = false;
			}
			if (event.keyCode == 38) {
				press_up = false;
			}
			if (event.keyCode == 39) {
				press_right = false;
			}
			if (event.keyCode == 40) {
				press_down = false;
			}
		}
		public function on_enter_frame(event:Event) {
			if (press_left) {
				trace("left");
			}
			if (press_right) {
				trace("right");
			}
			if (press_up) {
				trace("up");
			}
			if (press_down) {
				trace("down");
			}
			if (press_space) {
				trace("space");
			}
		}
	}
}

As you can notice, it’s not that easy to use the code that checks for key pressed because is made by lines 7-11, lines 14-15 and lines 17-50.

Obviously you can cut/paste them but it’s easy to forget some instructions and make errors.

If you want to write good code, you should make a class looking for pressed buttons and use it from the main file.

This is an example of the class:

package {
	import flash.events.KeyboardEvent;
	public class keys {
		private var press_left = false;
		private var press_right = false;
		private var press_up = false;
		private var press_down = false;
		private var press_space = false;
		public function keys(movieclip) {
			movieclip.stage.addEventListener(KeyboardEvent.KEY_DOWN, key_down);
			movieclip.stage.addEventListener(KeyboardEvent.KEY_UP, key_up);
		}
		public function is_left() {
			return press_left;
		}
		public function is_right() {
			return press_right;
		}
		public function is_up() {
			return press_up;
		}
		public function is_down() {
			return press_down;
		}
		public function is_space() {
			return press_space;
		}
		public function key_down(event:KeyboardEvent) {
			if (event.keyCode == 32) {
				press_space = true;
			}
			if (event.keyCode == 37) {
				press_left = true;
			}
			if (event.keyCode == 38) {
				press_up = true;
			}
			if (event.keyCode == 39) {
				press_right = true;
			}
			if (event.keyCode == 40) {
				press_down = true;
			}
		}
		public function key_up(event:KeyboardEvent) {
			if (event.keyCode == 32) {
				press_space = false;
			}
			if (event.keyCode == 37) {
				press_left = false;
			}
			if (event.keyCode == 38) {
				press_up = false;
			}
			if (event.keyCode == 39) {
				press_right = false;
			}
			if (event.keyCode == 40) {
				press_down = false;
			}
		}
	}
}

To use it, you just have to save it as keys.as in the same path of the main file, that at this time you will change this way:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class all_in_one extends Sprite {
		public function all_in_one() {
			var my_sprite = new Sprite();
			addChild(my_sprite);
			my_input = new keys(my_sprite);
			stage.addEventListener(Event.ENTER_FRAME,on_enter_frame);
		}
		public function on_enter_frame(event:Event) {
			if (my_input.is_left()) {
				trace("left");
			}
			if (my_input.is_right()) {
				trace("right");
			}
			if (my_input.is_up()) {
				trace("up");
			}
			if (my_input.is_down()) {
				trace("down");
			}
			if (my_input.is_space()) {
				trace("space");
			}
		}
	}
}

Notice at line 6 and 7 I created a sprite, and at line 8 I declared a keys object (the same name as the class file).

Then at lines 12, 15, 18, 21 and 24 I called class functions such as is_down, is_space and so on.

Last but not least, I have a class I can use in every platform game project.

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

214 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
// 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