Flash Game Tutorial: Shooting Bullets

In this tutorial I will show you how to make your game character shoot missles (or whatever object you want your character to shoot). This is mainly useful for making a shooting game, but it can also be used in other types of games where shooting is not the main focus. I will show you how to shoot with the spacebar and also how to shoot on mouse click.

If you have not already created a game character Player with one of my other tutorials, visit either Control Character with Mouse or Move Character with Arrow Keys, depending on how you want to control your game character.

In your flash file, draw whatever object you would like to be your bullet.

Select the image and convert it to a movie clip: Modify> Convert to Symbol

Name it Bullet, select Movie Clip as the type, under Linkage select export for actionscript and give it an Identifier and Class name Bullet. Click okay to return to the stage.

Now, create a new actionscript file: File> New> ActionScript File

Name it Bullet and save it in the same folder as your .fla file.

In this tutorial, the bullets will shoot vertically and be removed when they reach the top of the stage.

Here is the code for our Bullet class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Bullet extends MovieClip
{
    var speed;
   
    function onLoad()
    {
        speed = 30;
    }

    function onEnterFrame()
    {
        _y -= speed;
        if(_y < -10)
        {
            this.removeMovieClip();
        }
    }  
}

Line 3: We name a variable speed that will control how fast the bullet moves.

Line 5-8:When the Bullet movie clip loads, the variable speed is set to 20.

Line 12: Under onEnterFrame, the y coordinate of the Bullet movie clip decreases by the amount of the variable speed (so the bullet shoots vertically).

Line 13-16: If the y coordinate of the Bullet is less than -10, the Bullet is removed from the stage. We remove it once it is out of sight so we don’t see it pop off the stage and so it doesn’t go on infinitely.

In the Bullet class we program how the Bullet movie clip will behave once it is on the stage, but we still need to attach it to the stage when the spacebar is pressed or the mouse is clicked.

Shooting on Spacebar Press

If you have programmed arrow key movement for your game character, you will want to fire bullets by pressing the spacebar.

You will have to decide how close together the bullets can be fired to prevent a continuous stream when the spacebar is held down.

Here the bullets are spaced out by creating a timer that only allows a bullet to be fired every four frames.

Here is the code we need to add to our Player class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Player extends MovieClip
{
    var shootSpacer;
   
    function onLoad()
    {
        shootSpacer = 0;
       
    }

    function onEnterFrame()
    {
        shootSpacer += 1;
           
        if( Key.isDown(Key.SPACE) && shootSpacer> 4)
        {
            shootSpacer = 0;
            var bullet = _root.attachMovie("Bullet","Bullet" + _root.getNextHighestDepth(), _root.getNextHighestDepth());
            bullet._x = _x;
            bullet._y = _y;
        }
    }
   
}

Line 3: We name a variable shootSpacer that will act as a timer to space out the bullets.

Line 7: When the movie clip is loaded shootSpacer will be set to zero.

Line 13: Under onEnterFrame() the shootSpacer is increased by one.

Line 15-18: If the spacebar is pressed and the timer shootSpacer has reached a number greater than four, then the timer will be reset and a Bullet movie clip is attached to the stage.

Line 19-20: The bullet is attached to the Player movie clip at its 0,0 coordinates.

If you want to attach the bullet to a different part of the Player movie clip you can add or subtract pixels from the _x and _y in lines 19 and 20.

Shooting on Mouse Click

If you have programmed mouse control for your game character, you probably want to shoot on the click of the mouse button.

After programming the Bullet class as explained above, you will need to add code to your existing Player class.

Add the code in the onEnterFrame() event handler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Player extends MovieClip
{

    function onEnterFrame()
    {
        onMouseDown= function()
        {
                var bullet = _root.attachMovie("Bullet","Bullet" + _root.getNextHighestDepth(), _root.getNextHighestDepth());
                bullet._x = _x;
                bullet._y = _y;
        }
    }
   
}

Line 6-8: When the mouse is pressed, a Bullet movie clip is named as a variable bullet and is attached to the Player.

Line 9-10: The bullet’s x and y coordinates are same as the 0,0 location of the Player movie clip when it is attached.

As explained above, you can also adjust the position of the bullet by adding or subtracting from the _y and _y coordinated of the Player in Lines 9 and 10.

After it is attached, the Bullet behaves according to the programming of the Bullet class.

You can also limit the spacing of the bullets by adding the shootSpacer code that is given above in section about shooting with the spacebar.

I will cover collision testing and hitting enemies or targets in another tutorial.

Here is the game character shooting bullets … or apples, same thing.

Flash game tutorial shooting objects

Flash Game Tutorial: Control Character with Mouse

Controlling your game character with the mouse has many advantages over keyboard control. The character can move more fluidly in all directions, rather than a rigid up-down-right-left movements. Mouse control is more intuitive and natural, particularly for people who do not play games regularly. And you can use the mouse button to shoot or perform some other action in the game.

I will be showing you how to control your game character with the mouse with precise movements. I will also show how to create lag in the character’s movement to give it a loose, floating effect. And lastly, we will hide the cursor so it really feels like you are moving the game character.

How to Control Game Character with Mouse-Precisely

First, open an AS 2 flash file: File> New> Flash File (ActionScript 2.0) and draw your game character image. Select your game character and go to Modify> Convert to Symbol.

Name it Player and select Movie clip as the type. Under Linkage check the box export for actionscript and put Player as the Identifier and the Class. Click okay and you are back to the stage.

Now create a new actionscript file: File> New> ActionScript File. Save this actionscript file in the same folder as your .fla file and name it Player.

In our Player class we will write the code that controls the game character movie clip, Player.

Here is the code that will go in our Player actionscript file and the explanation follows.

1
2
3
4
5
6
7
8
9
class Player extends MovieClip
{
   
    function onEnterFrame()
    {    
        this._x = _root._xmouse;
        this._y = _root._ymouse;
    }
 }

Line 6: We set the x coordinate of Player equal to the x coordinate of the mouse on the stage.

Line 7: We set the y coordinate of Player equal to the y coordinate of the mouse on the stage.

Code placed in the onEnterFrame event handler is executed continually at the frame rate so we now have continuous mouse control over our Player movie clip.

The mouse cursor will appear over the crosshair in your movie clip. If you want to reposition it so the cursor is not covering your character image, double click the movie clip in your .fla file and place the image wherever you like near the crosshair. Or you can hide the mouse cursor, as I explain below.

Mouse control with precise movement:

Mouse control with precise movements.

How to Create Lag in your Game Character Movement

Lagging character movement provides a different aesthetic for a game; it is good for making the game character seem like they are floating or moving underwater. It also affects the gameplay, often making a game more difficult. The person playing the game has to have more finesse in order to be successful.

To create this effect:

Follow the directions above for creating your game character movie clip, Player.

Open or create an actionscript document named Player.

Here is the code for our Player class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Player extends MovieClip
{
   
    function onEnterFrame()
    {    
        var xMouse = _root._xmouse;
        var yMouse = _root._ymouse;
        if(Math.abs(xMouse - this._x) < 1)
        {
            this._x = xMouse;
            this._y = yMouse;
        }
        else
        {
            this._x -= (this._x-xMouse) / 7;
            this._y -= (this._y-yMouse) / 7;
        }
    }  
}

Line 6-7: We set the variables xMouse and yMouse equal to the x and y positions of the Player movie clip on the stage.

Line 8-12: If the absolute value of the variable xMouse minus the x coordinate of Player is less than one, then the Player x and y coordinates will be the same as the x and y coordinates of the mouse. If the Player is less than one pixel away from the mouse cursor, it will be placed at the exact position as the mouse cursor.

Line 13-17: Otherwise, the distance between the Player movie clip and the cursor will decrease incrementally at a rate determined by subtracting the position of the cursor from the position of the Player and dividing by 7.

You can increase the number it is divided by to create a greater lag or you can decrease that number to lessen the lag. It depends on how great of control you want over the Player movie clip.

Mouse control with lagging movement:

Lagging mouse control.

How to Hide the Mouse Cursor

With the cursor hidden, the focus is on the game character. There is no chance that the character will be covered up by the cursor and it feels like you are controlling the game character, rather than leading them with the mouse. Hiding the mouse cursor is very simple.

In our Player actionscript file, we add the following code right above the function onEnterFrame().

1
2
3
4
    function onLoad()
    {
        Mouse.hide();  
    }

Line 1-4: When the Player movie clip loads, the mouse cursor is hidden.

Mouse control with the cursor hidden and lagging movement:

Hide mouse cursor.

Flash Game Tutorial: Adding Randomly Falling Objects

Randomly falling objects can be one of the main elements of a flash game. You can create randomly falling objects that the player has to collect or they can be objects that must be avoided. Regardless of whether you want to make objects that give you points, make you lose health or enable you to fly, you can use this method to create them.

I will show you how to create randomly falling stars for your game, using two classes, one for your game character: Player, and one for the Star movie clip: Star. This tutorial uses object oriented programming and assumes you have a main class, Player, that controls your game character. If you have already created a flash file based on my tutorial Move Character with Arrow Keys, you can open that and work from there.

Otherwise create a Flash file: File> New> Flash File (ActionScript 2)

Draw the Object in Your Flash File

Set the stage to 450px wide by 300px tall in the properties window.

Draw whatever object you would like to fall across the screen. If you want to follow the tutorial, draw a star.

Convert the image to a movie clip: Modify> Convert to Symbol

Name it Star (or whatever your object is), check the box next to export for actionscript, and put Star for the Identifier and Class.

Click okay and you are back to the stage.

Create a Star Class

Now create a new actionscript file: File> New> ActionScript File

Save it as Star and make sure it is in the same location as your .fla file.

Here is the code for our Star class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Star extends MovieClip
{
    var speed;

    function onLoad()
    {
        speed = Math.random()*10+5;
        _x = Math.random()*400+50;
        _y = -10;
    }

    function onEnterFrame()
    {
        _y += speed;
        _rotation -= 5;

        if(_y > 310)
        {
            this.removeMovieClip();
        }
    }

}

In the Star class we want to define how a Star movie clip will behave when it is attached to the stage.

Line 3: We name a variable speed to control how fast the star will move.
Line 7: Under onLoad() we set the speed equal to a random number between 1 and 10 plus five. The minimum speed will be 6 and the max will be 15.
Line 8: We position it randomly on the x axis, taking into account the width of our stage.
Line 9: We position it 10 pixels above the stage so it does not appear suddenly on the stage, but rather falls from above.
Line 14-15: Under onEnterFrame() we give it speed in the y direction and a counter clockwise rotation so that the stars slowly spin as they fall.
Line 17-20: When the star reaches ten pixels past the end of our stage, it is removed.

That is it for our star class. But we still need to attach the stars to the stage. We will do that using a timer in our Player class.

Create a Player Class

You will need a movie clip that is linked to a Player class, in order to create random falling objects with this method. If you do not already have a movie clip linked to a Player class, follow the directions below and visit Move Character with Arrow Keys if you would like to program arrow key movement for your game character.

To Create Player Movie Clip

Draw your game character. Select the image and go to Modify> Convert to Symbol. Name it Player. Select Movie Clip as the type, under Linkage check the box for export for actionscript and put Player as the Identifier and the Class. Click okay to return to the stage.

Now create a new actionscript file: File> New> Actionscript File. Go to File>Save Name it Player and save it in the same folder as your .fla file. Or open your existing player class.

Here is the code for our Player class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Player extends MovieClip
{
    var starTimer;

    function onLoad()
    {
        starTimer = 0;

    }

    function onEnterFrame()
    {
        starTimer += 1;
        if(starTimer > 5)
        {
            starTimer = 0;
            var star = _root.attachMovie("Star", "Star" + _root.getNextHighestDepth(), _root.getNextHighestDepth());
        }

    }
}

Line 3: We define a vaiable, starTimer, that will keep track of how often a star is placed on the stage.
Line 7: Under onLoad() the starTimer is set to zero.
Line 13: Under onEnterFrame() we start the timer and have it increase by increments of one.
Line 14-18: If the starTimer is greater than five, the timer will be reset and an instance of our movie clip Star will be added to the stage. The timer runs continually and every time the Star timer reaches 5 a star is added. You can increase the timer to decrease the number of stars, or decrease the timer to increase the number of stars appearing on the stage.

Now the stars will be attached to the stage through the player class, so you can delete the star movie clip from the stage in your .fla file. Make sure you have that game character that is linked to the Player class on the stage though, or no stars will appear. If you are not making a game, but still want to use this method to create randomly falling objects, you can make an empty or invisible movie clip on the stage and link it to a Player class with the timer code.

That is it for creating randomly falling objects.

Here are our falling stars:

Flash Tutorial: Create Random Falling Objects

Flash Game Tutorial: Create a Scrolling Background

A scrolling background is a simple way to make it look like your game character is going somewhere. You can make it so your character appears to be falling from the sky, floating through space, running through meadows, etc. I am going to show you how to create a background that scrolls at a constant speed, regardless of the character’s movements. This is a different effect than scrolling when the character is moving or when the character gets to the edge of the screen.

First open a Flash AS2 document: File> New> Flash File (ActionScript 2)

Then draw the background you would like to scroll. Make it very wide if you would like it to scroll horizontally or very tall if you want it to scroll vertically. In this tutorial we are going to make the background scroll vertically. To follow this example, make its height 900px and set your stage height to 300px in the properties window.

Select your entire background image.

Go to Modify> Convert to Symbol

Name it Background (or a name of your choosing) and select Movie Clip. Under linkage select export for actionscript and put Background as the Identifier and Class.

Click okay and you are back to the stage.

Make sure that the crosshair of the selected movie clip aligns with the top left of the Background image. Change it by double clicking to edit the symbol, selecting the entire image and entering zero in the x and y boxes of the properties window.

When you position the Background movie clip on the stage make it aligned with the top of the stage. You can either do this visually or set its x and y positions to zero in the properties window.

Now create a new actionscript file: File> New> ActionScript File

Here is the code that will go in our actionscript file. Explanation follows.

1
2
3
4
5
6
7
8
9
10
11
class Background extends MovieClip
{
    function onEnterFrame()
    {
        _y -= 4;
        if(_y < -600)
        {
            _y = 0;
        }
    }
}

Line 1-2: Defines the class to which we linked our background movie clip in our .fla file.

Line 3-5: Under onEnterFrame() we set the rate at which the background will scroll and the direction. Here we specify it will move four pixels in the negative y direction. This will be processed continually at the frame rate of the movie because it is defined within the onEnterFrame() event handler.

Line 6-9: When it has scrolled down 600px, it starts from the beginning. For this example we reset it at 600 because our stage has a height 300px and the movie clip is 900px tall. We want it to restart when the last 300px are on the stage so no white space appears where the movie clip ends.

Because we are scrolling along the y axis in the negative direction, our character will appear to be falling, as the background scrolls upward. You can replace each y with an x to scroll horizontally and change the minus sign on line 5 to a plus sign to change directions. If you want the background to scroll in the other direction, remember that you will also have to position it differently on the stage, in your .fla file. And of course, if you want it to scroll horizontally you will have to make your image very wide, instead of tall.

In order for the background to scroll seamlessly you must make the first section of the background that appears on the stage identical to the last section that appears on the stage, with the exception of a few pixels to account for the slight movement that should occur. That way when it starts at zero, it won’t suddenly jump to a different image than what was just on the screen.

Here is the scrolling background: I’ve shown it with a game character that moves only left and right when you press the arrow keys, so it appears that he is falling. Click on image before attempting movement with arrow keys.

Flash Scrolling Background Example