Create a Flash game like Pixel Purge step 3 – Fire rate and spread

Read all posts about "" game

As promised, here I am with the 3rd part of this tutorial, showing you how to manage fire rate and multiple bullets. Moreover, I made some changes to bullet_mc class following the suggestions Harack left in the comments of step 2.

To manage fire rate, we need to set up a timer each time the player fires a bullet. Then, while such timer is active, the player won’t be able to fire even if he keeps pressing left mouse button. To deal with fire spread, we’ll simply fire bullets at different angles.

These are the new variables used in this script:

private var fire_delay:uint=250;: represents the delay, in milliseconds, between a bullet and another

private var delay:Timer=new Timer(fire_delay);: this is the timer which will handle the fire delay. If you want to have more information about AS3 Timer class, refer to Understanding AS3 Timer Class.

private var delay_completed:Boolean=true;: a boolean variable used to inform us the delay between a bullet and the next one to be fired is over. If it’s true, you can fire again.

private var bullets_per_time:uint=3;: this variable will tell the script how many bullets will be fired at once.

private var bullets_angle=10*0.0174532925;: and this is the difference angle between a bullet and another, in radians. 0.0174532925 is what converts degrees to radians.

Now the main class changes this way:

package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.geom.Point;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    public class main extends Sprite {
        private var game_container:game_container_mc;
        private var player:player_mc;
        private var left,up,right,down:Boolean;
        private var crosshair:crosshair_mc;
        private var firing:Boolean=false;
        private var bullet:bullet_mc;
        private var fire_delay:uint=250;
        private var delay:Timer=new Timer(fire_delay);
        private var delay_completed:Boolean=true;
        private var bullets_per_time:uint=3;
        private var bullets_angle=10*0.0174532925;
        public function main() {
            left=up=right=down=false;
            game_container=new game_container_mc();
            addChild(game_container);
            player=new player_mc();
            game_container.addChild(player);
            crosshair=new crosshair_mc();
            addChild(crosshair);
            stage.addEventListener(KeyboardEvent.KEY_DOWN,on_key_down);
            stage.addEventListener(KeyboardEvent.KEY_UP,on_key_up);
            addEventListener(Event.ENTER_FRAME,on_enter_frame);
            addEventListener(MouseEvent.MOUSE_DOWN,on_mouse_down);
            addEventListener(MouseEvent.MOUSE_UP,on_mouse_up);
        }
        private function on_mouse_down(e:MouseEvent):void {
            firing=true;
        }
        private function on_mouse_up(e:MouseEvent):void {
            firing=false;
        }
        private function on_enter_frame(e:Event):void {
            crosshair.x=mouseX;
            crosshair.y=mouseY;
            if (left) {
                player.engine(-1,0);
            }
            if (right) {
                player.engine(1,0);
            }
            if (up) {
                player.engine(0,-1);
            }
            if (down) {
                player.engine(0,1);
            }
            player.move_player();
            game_container.move_container(player.x,player.y);
            if (firing&&delay_completed) {
                var spreading_angle:Number = (bullets_per_time-1)*bullets_angle
                delay_completed=false;
                delay.addEventListener(TimerEvent.TIMER, on_delay_over);
                delay.start();
                for (var i:uint=0; i

The interesting part is the one which manages the firing: at line 58 you can see the player can fire if firing is true (mouse button is pressed) and delay_completed is true too (at least fire_delay milliseconds passed since the last bullet has been fired).

Then delay_completed is set to false (line 60) and a listener is created to count fire_delay milliseconds (lines 61 and 62).

on_delay_over function at lines 72-76 sets delay_completed to true again and removes the listener.

At lines 63-68 firing x and y speeds are calculated before passing them to bullet_mc class, according to Harack's suggestions, and the spread angle is determined in a way similar to the rays of light you encountered in Create a survival horror game in Flash – AS3 version. And there's nothing more to say, since the rest of the script is just a collection of old concepts you can find here and there in the blog.

And this is bullet_mc class. As you can see, no more trigonometry in it.

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class bullet_mc extends Sprite {
		private var speed:uint=25;
		private var vel_x:Number;
		private var vel_y:Number
		public function bullet_mc(px:int,py:int,vx:Number,vy:Number) {
			x=px;
			y=py;
			vel_x=vx;
			vel_y=vy;
			addEventListener(Event.ENTER_FRAME,on_enter_frame);
		}
		private function on_enter_frame(e:Event) {
			x-=speed*vel_x;
			y-=speed*vel_y;
			if (x>1280||x<0||y>960||y<0) {
				removeEventListener(Event.ENTER_FRAME,on_enter_frame);
				var par:main= this.parent.parent as main
				par.remove_bullet(this);
			}
		}
	}
}

This is the result:

Move the ship with arrow keys, aim and fire with the mouse.

Download the source code. Next step, the enemy!!

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