Create a Flash game like The Impossible Line step 2 – the collision sensor

Read all posts about "" game

Welcome to the second step of the series. In the first step we created the basics of The Impossible Line game, now it’s time to add the collision sensor.

In the original game, once you start moving your finger, walls and obstacles disappear, forcing you to remember their initial position.

To help you, a red collision sensor in the top right of the screen will get smaller and smaller as you are getting closer and closer to walls, acting something like a parking sensor.

This means every time the player moves the arrow, we have to check for the closest distance between the arrow and the wall, and update collision sensor size accordingly.

The basics of this feature are taken from the post Create a survival horror game in Flash – AS3 version: I just cast a series of rays looking for obstacles, and return the shortest ray.

This is the modified class, new lines are highlighted and fully commented:

package {
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	public class Main extends Sprite {
		// canvas where we'll draw the line
		private var canvas:Sprite = new 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;
		// anglePoint is the latest point we checked to determine angle of movement
		private var anglePoint:Point;
		// starting thickness of the line we are drawing. I am changing it often to give some kind of chalk effect
		private var thickness:Number=3;
		// 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 radar image
		private var radar:Radar=new Radar();
		// radarCanvas is just for debuggin purpose
		private var radarCanvas:Sprite=new Sprite();
		public function Main() {
			// adding the canvas to stage
			addChild(canvas);
			// 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;
			// adding radar canvas
			addChild(radarCanvas);
			// at this time we only have to wait for the player to press the mouse button
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
		}
		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);
			anglePoint=new Point(mouseX,mouseY);
			// placing the graphic pencil under arrow Sprite
			canvas.graphics.moveTo(arrow.x,arrow.y);
		}
		private function mouseMoved(e:MouseEvent):void {
			// the player is moving the mouse, so he's drawing
			// let's set the line style
			canvas.graphics.lineStyle(thickness,0xffffff);
			// finding the horizontal and vertical distances between current mouse position and last saved mouse position;
			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;
			// drawing to current arrow position
			canvas.graphics.lineTo(arrow.x,arrow.y);
			// saving current mouse position;
			mousePoint.x=mouseX;
			mousePoint.y=mouseY;
			// if the distance between current mouse point and the last point where we updated arrow rotation
			// is greater than 20 pixels, let's rotate arrow sprite according to the angle and save
			// current mouse position in anglePoint Point
			if ((anglePoint.x-mouseX)*(anglePoint.x-mouseX)+(anglePoint.y-mouseY)*(anglePoint.y-mouseY)>400) {
				var angle:Number=Math.atan2(anglePoint.y-mouseY,anglePoint.x-mouseX);
				arrow.rotation=angle*57.2957795-90;
				anglePoint.x=mouseX;
				anglePoint.y=mouseY;
			}
			// increasing line thickness by a random value that can be -1, 0 or 1
			thickness=thickness+Math.floor(Math.random()*3)-1;
			// keeping thickness between 2 and 5
			if (thickness<2) {
				thickness=2;
			}
			if (thickness>5) {
				thickness=5;
			}
			// preparing debug canvas
			radarCanvas.graphics.clear();
			radarCanvas.graphics.lineStyle(0,0xff0000);
			// 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) {
					radarCanvas.graphics.moveTo(arrow.x,arrow.y);
					radarCanvas.graphics.lineTo(arrow.x+j*Math.cos(rayAngle), arrow.y+j*Math.sin(rayAngle))
					// 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
		}
		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);
		}
	}
}

And this is the result:

Drag mouse around the screen and see what happens to the top right collision sensor when you get too close to walls. To show you what happens, I am drawing the rays used to scan for walls.

Download the source code.

Next time, power-ups and replay, and we’ll have the final prototype.

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