Aeroplane Shooting Game Tutorial – Shooting Bullets

admin  

Part 2 - Shooting Bullets

In this tutorial we are adding the functionality to make the player plane to shoot bullets. The easiest way would be to shoot a bullet each time the player press the fire button. A little more elaborate method is to shoot bullets when the fire button is down and to stop shooting when is released. In either case we need to implement a cool down method between shooting bullets.

When we deal with such object like the bullets we must destroy them when they are not necessary anymore. The player bullets fly vertically until they get out of the screen. When they do so, we have to remove them.

We are adding the following members to our class:

private var playerBullets:Vector.<MovieClip> = new Vector.<MovieClip%gt;();
    private var playerBulletsDelay:Number = 0;

    private var BULLET_SPEED:Number = 6;

After that, for each frame we compute the elapsed time from the last frame. We also check the time elapsed since last bullet was shoot. If the fire key is pressed and the cool down time is over we shoot the next bullet. In the function, for each frame we update the bullets positions and we remove the bullets which are getting out of the screen.

private var lastFrameTime:Number = (new Date()).getTime();
        
    private function enterFrame(e:Event):void
    {
        var thisFrame:Date = new Date();
        var dt:Number = (thisFrame.getTime() - lastFrameTime) / 1000;
        lastFrameTime = thisFrame.getTime();
            
        ...
            
        // shoot
        playerBulletsDelay -= dt;
        if (isFire() 
            && playerBulletsDelay <= 0) { playerBulletsDelay = 0.3; shootPlayerBullet(); } // update bullees positions for each( var b:MovieClip in playerBullets) { b.y -= BULLET_SPEED; } // remove bullets which are getting out of the screen while(playerBullets.length > 0 && playerBullets[0].y < -10)
        {
            this.removeChild(playerBullets.shift());
        }
    }

Here you can play the result of this tutorial(Ctrl to fire):

The code is for this tutorial is shared on github. Each part is tagged so in order to see the code for this tutorial just check the Part 2 tag. Here is the link.