Create a Flash game like The Impossible Line – Final prototype

Read all posts about "" game

As promised, here is the final prototype of The Impossible Line game.

In first step I showed you how to draw following mouse movement.

In second step I showed you how to create the collision radar.

In this big update I am introducing the remaining features:

* Goal: you now have to reach the green circle at the right of the stage.

* Death: happens when you hit a wall.

* Light powerup: in the original game you activate it with an icon, in this version you have to touch it to activate it. I am using the same principle seen in the second step to create the radar, together with some gradient fill to achieve quite the same effect you can see in the original game.

* Replay: once you win or lose the game, you can see the replay of your action. This is an amazing feature which can be done just recording player position at every frame by storing it into a vector, then moving the player according to vector values.

To make everything fit into a quite small and still readable full commented script, I removed some basic features introduce at step 1 such as drawing and rotating.

You should be able to add them by yourself in a matter of seconds. Here is the script:

package {
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.display.GradientType;
	import flash.geom.Matrix;
	import flash.events.Event;
	public class Main extends Sprite {
		// Arrow is the name class you can find in the library containing the arrow image
		private var arrow:Arrow=new Arrow();
		// mousePoint is the actual point we are moving the mouse on
		private var mousePoint:Point;
		// Level is the name of the class you can find in the library storing levels
		private var level:Level=new Level();
		// Radar is the name of the class you can find in the library storing radar image
		private var radar:Radar=new Radar();
		// Light is the name of the class you can find in the librart storing light image
		private var light:Light=new Light();
		// Goal is the name of the class you can find in the librart storing goal image
		private var goal:Goal=new Goal();
		// lightCanvas is the sprite where we'll display the light
		private var lightCanvas:Sprite=new Sprite();
		// Boolean variable to see if we collected the light
		private var hasLight:Boolean=false;
		// vector to store all mouse movements
		private var mouseVector:Vector.<Point>=new Vector.<Point>();
		// Boolean variable to tell us if we shoud record mouse movements
		private var recordMouse:Boolean=false;
		// Boolean variable to tell us if we shoud play mouse movements
		private var playMouse:Boolean=false;
		public function Main() {
			// adding the arrow in the upper left corner of the stage
			addChild(arrow);
			arrow.x=40;
			arrow.y=40;
			// adding the level to stage
			addChild(level);
			// adding the radar in the upper right corner of the stage
			addChild(radar);
			radar.x=600;
			radar.y=40;
			// placing the light in the middle of the stage
			addChild(light);
			light.x=320;
			light.y=240;
			// adding light canvas
			addChild(lightCanvas);
			// placing the goal in the right end of the stage
			addChild(goal);
			goal.x=600;
			goal.y=240;
			// at this time we only have to wait for the player to press the mouse button
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
			// a listener to give a flickering effect to the light and record mouse movements
			addEventListener(Event.ENTER_FRAME,update);
		}
		private function mousePressed(e:MouseEvent):void {
			// the player pressed the mouse so we can start drawing - we don't need to wait for the player to press the mouse
			stage.removeEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
			// now we must wait for the player to move or release mouse button
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
			stage.addEventListener(MouseEvent.MOUSE_UP,mouseReleased);
			// saving mouse position
			mousePoint=new Point(mouseX,mouseY);
			// hiding the level;
			level.visible=false;
			// let's start recording mouse movements
			recordMouse=true;
		}
		private function mouseMoved(e:MouseEvent):void {
			var dx:Number=mouseX-mousePoint.x;
			var dy:Number=mouseY-mousePoint.y;
			// moving arrow Sprite according to such distances
			arrow.x+=dx;
			arrow.y+=dy;
			// saving current mouse position;
			mousePoint.x=mouseX;
			mousePoint.y=mouseY;
			// a couple of temporary variables
			var rayAngle:Number;
			// precision is the... precision of the radar system. I suggest a number which divides 360
			var precision:Number=20;
			// rayStep is the number of steps in pixels the raycast performs to find an obstacle
			var rayStep:Number=1;
			// default minimum distance is 50 pixels
			var minDistance:Number=50;
			// looping and looking for the closest point to the arrow
			for (var i:Number=0; i<=precision; i++) {
				// finding the i-th angle
				rayAngle=2*Math.PI/precision*i;
				// arrow radius is 16px. We are looking for obstacles closer than 50px. So we must see from 16 to 66
				// the bigger rayStep, the faster and less accurate the process
				for (var j:Number=16; j<=66; j+=rayStep) {
					// here we go, looking for obstacles
					if (level.hitTestPoint(arrow.x+j*Math.cos(rayAngle),arrow.y+j*Math.sin(rayAngle),true)) {
						// we found it!!
						minDistance=Math.min(j-16,minDistance);
						break;
					}
				}
			}
			// updating radar size;
			radar.width=minDistance;
			radar.height=minDistance;
			// you hit the wall = game over
			if (minDistance<1) {
				mouseVector.push(new Point(arrow.x,arrow.y));
				level.visible=true;
				stage.removeEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
				stage.removeEventListener(MouseEvent.MOUSE_UP,mouseReleased);
				removeChild(lightCanvas);
				removeChild(radar);
				recordMouse=false;
				playMouse=true;
			}
			// checking the collision between the arrow and the light, if we still did not pick up the light
			if (! hasLight) {
				var arrowToLightX:Number=arrow.x-light.x;
				var arrowToLightY:Number=arrow.y-light.y;
				// 676 = (16 (arrow radius) + 10 (light radius))^2
				if (arrowToLightX*arrowToLightX+arrowToLightY*arrowToLightY<676) {
					// you got light powerup!!
					hasLight=true;
					removeChild(light);
				}
			}
			else {
				// do you remember the radar? Things are quite similar for the light, we only want more precision
				lightCanvas.graphics.clear();
				lightCanvas.graphics.lineStyle(0,0xffffff,0);
				var mtx:Matrix = new Matrix();
				mtx.createGradientBox(232,232,0,arrow.x-116,arrow.y-116);
				// we are drawing a gradient this time;
				lightCanvas.graphics.beginGradientFill(GradientType.RADIAL,[0xffffff,0xffffff],[0.5,0],[0,255],mtx);
				precision=60;
				for (i=0; i<=precision; i++) {
					rayAngle=2*Math.PI/precision*i;
					for (j=16; j<=116; j+=rayStep) {
						if (level.hitTestPoint(arrow.x+j*Math.cos(rayAngle),arrow.y+j*Math.sin(rayAngle),true)) {
							break;
						}
					}
					if (i==0) {
						// moving the graphic pen if it's the first point we find
						lightCanvas.graphics.moveTo(arrow.x+j*Math.cos(rayAngle), arrow.y+j*Math.sin(rayAngle));
					}
					else {
						// or drawing if it's not the first point we find
						lightCanvas.graphics.lineTo(arrow.x+j*Math.cos(rayAngle), arrow.y+j*Math.sin(rayAngle));
					}
				}
				lightCanvas.graphics.endFill();
			}
			// checking the collision with the goal;
			var arrowToGoalX:Number=arrow.x-goal.x;
			var arrowToGoalY:Number=arrow.y-goal.y;
			// 1296 = (16 (arrow radius) + 20 (goal radius))^2
			if (arrowToGoalX*arrowToGoalX+arrowToGoalY*arrowToGoalY<1296) {
				// great! you won!
				mouseVector.push(new Point(arrow.x,arrow.y));
				level.visible=true;
				stage.removeEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
				stage.removeEventListener(MouseEvent.MOUSE_UP,mouseReleased);
				removeChild(lightCanvas);
				removeChild(radar);
				recordMouse=false;
				playMouse=true;
			}
		}
		private function mouseReleased(e:MouseEvent):void {
			// the player released the mouse. Stop drawing and let's wait for mouse press
			stage.removeEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
			stage.removeEventListener(MouseEvent.MOUSE_UP,mouseReleased);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
		}
		private function update(e:Event):void {
			// just flickering the light
			lightCanvas.alpha=0.5+Math.random()*0.5;
			// recording mouse position
			if (recordMouse) {
				mouseVector.push(new Point(arrow.x,arrow.y));
			}
			// playing mouse position
			if(playMouse){
				var currentPoint:Point=mouseVector.shift();
				arrow.x=currentPoint.x;
				arrow.y=currentPoint.y;
				if(mouseVector.length==0){
					removeEventListener(Event.ENTER_FRAME,update);
					}
			}
		}
	}
}

And this is the result:

Move the white circle to the green circle avoiding white walls and looking at the red radar. Get the yellow circle to turn on the light. Refresh once you win or die.

Download the source code. Next time, I am going to show you how to port it to iPad using Starling.

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
// Mini Archer
// 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
// 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