Skip to content

Seifer Tim's Tutorial

Rybar edited this page Sep 13, 2010 · 38 revisions

Flixel Basic Game Tutorial

Please Note: This tutorial was recently updated for flixel 1.4x (at the time of this writing: 1.47). Please visit this thread for help or to report errors. -Rybar

by SeiferTim & DarthLupi

Contents:

PART 1
I. Introduction II. Getting Started III. Creating the Menu
i. MenuState
PART 2
IV. Getting Ready for the Playstate
i. Player
ii. Tilemaps – Creating the Game World
iii. Setting up the Playstate
V. Adding the Enemy to the Game VI. Fighting the Enemies
i. Make the Weapon
ii. Equip the Player
iii. Update the PlayState
PART 3
VII. The Enemies Fight Back! VIII. Keeping Score
i. Health
IX. Spawning Enemies

I. Introduction

The goal of this Tutorial is to walk you through the process of starting a very basic Flixel Platform Game, while explaining and demonstrating some of the key functions and pieces of Flixel so that you can utilize them for future projects of your own. We will also explore some of the avenues to further expand on the basic concepts to help you explore and learn on your own.

Do not be overwhelmed with any of the information in the Getting Started section. Once you understand the basic concepts we cover there, the rest of the tutorial will come together for you nicely. Don’t expect to simply copy and paste code from this tutorial either, as it is meant to give you a base, and get you accustomed to entering code within FlashDevelop as well. There will be full code segments early on for you to check yourself with to make sure you are starting properly, but by the end you should be accustomed to the process enough to enter code without it. Due to this purpose, actual files will not be made available for download.

The Tutorial is going to require a few things of you if you intend to get the most out it:

You are not going to make the next Cave Story with this tutorial. However, with some of the items presented within, and with a little ambition to learn more on your own, you should be able to create almost any type of game you want with Flixel.

Back to Contents

II: Getting Started

1. First, you will need to download the Flixel framework, and then you can proceed to step 2.

2. Open FlashDevelop . From the menu at the top, click “Project” and choose “New Project…”

3. Choose “AS3 Project” from the list, and give your project a name, and a location. We’ll be using “Tutorial” for the name of this project.

4. Once Flixel has finished downloading, open and extract all the files to the src folder within your project’s folder.

5. You can delete the Main.as file that’s in your project, then make a new Class file to the src folder, and name it Tutorial.as . Right-click on this file and click “Always Compile”, then double-click the file to open it.

What this does is set this Class to compile when ever you press the play button or press F5.

6. You should see something that looks like this:

 package  
      {
          public class Tutorial
          {
              public function Tutorial()
              {

              }
          }
      }

This is the basic structure of a Class in AS3.

Programming Tip:
Classes are a method for making little programs that you can “call” as many times as you want and use in other parts of your code. This is really handy in game development because game objects can be defined in separate classes and used at will. Read More…

7. Now, in order to tell the project that we want to use Flixel, we have to import it. So, somewhere after the first { and before “public class Tutorial”, add a new line and type:

import org.flixel.*;

For this tutorial, we’re going to import everything – but in the future, you’ll want to actually pick the pieces you want to use.

Programming Tip:
Importing a class file is basically making all of it’s contents available to the rest of your program. In this case we use the asterisk (*) which loads all of the classes in the Flixel directory to be used by our game.

8. Next, we need to define the size of the movie, so in a new line under the import, add:

[SWF(width = "640", height = "480", backgroundColor = "#000000")]

This tells the project that we’re going to make a SWF file that is 640 pixels wide by 480 pixels high with a black background. Basically, you set the game’s display settings here. This is not the true resolution of the graphics. Those will be set later. Think of these settings as the window size.

9. In the next line, we’ll add the preloader:

[Frame(factoryClass="Preloader")]

We do not currently have a Preloader class in the project, but we will create that when we are done with the Tutorial class.

10. Next, we need to make this class (Tutorial) into a sort of copy of the FlxGame class. To do this, we make this class an ‘extension’ of the FlxGame class. To do this, find the line of code that says “public class Tutorial”. At the end of the line, add these two words:

extends FlxGame

What this does it tells the project that the Tutorial Class is basically the same as the FlxGame class, but with a different name, and your own stuff added to it.

Programming Tip:
Think of extending classes like drawing with tracing paper. The FlxGame class, which is the original class being extended, is drawn on the bottom layer, and the Tutorial class is on a piece of tracing paper on top of the FlxGame class. You can see all the lines on the bottom layer, and you can draw your own lines without actually changing the bottom layer. If at some time in the future FlxGame is changed – someone draws on the bottom layer – then those changes would be added to your class without any hassle. Other classes still using only the original class will not be affected by classes extending from it.

11. Next, we simply want to make the Tutorial constructor function within the class return data with a type of void. So change the line that says:

public function Tutorial()

to say

public function Tutorial():void
Programming Tip:
All functions need to return something. When you return void you simply returning nothing. Keep this in mind when you start writing your own functions.
Programming Tip:
This function is called a constructor. The constructor is used to setup initial behavior for a class. Every time a class is initially called into action, the constructor fires off once. The constructor should be the first function in a class, and shares the name of class. It can be used to declare variables and even call other functions or classes.

11. Since we set the Tutorial Class to “Always Compile”, the first class your program will fire off is the Tutorial class. It’s going to automatically call the Tutorial function within it, since that is the constructor of the class.

Now we are going make use of the fact that we extended FlxGame with the Tutorial class. To do that we are going to need to call super(), which is a function defined within FlxGame. What super() does, without any other function specified, is call the constructor of the class you are extending.

Because the Tutorial Class is an extension of FlxGame, we’re going to use FlxGame’s FlxGame function, it’s constructor, to initialize the game.

We do this by using “super” within the Tutorial function.

So, underneath where it says:

public function Tutorial():void
      {

Add these 2 lines of code:

super(320,240,MenuState,2);
super.setLogoFX(0xFFFFFFFF);

As you type this, FlashDevelop should pop up a tooltip to help you see what each parameter is.

You can also look up the FlxGame Class in the Flixel documentation, and see something like this:

function FlxGame (GameSizeX : uint, GameSizeY : uint, InitialState : Class, Zoom : uint)

So, the first parameter we send over is “GameSizeX”, or the width of the game in pixels. We defined it as 320. Next is “GameSizeY”, or the height of the game in pixels, which we set to 240. If you’ll notice, these numbers are half the numbers used in the settings for the window. This is the game’s true resolution.

“InitialState” is going to be the State class we want to start our game with – in our case it will be “MenuState” – we’ll need to create this later. “Zoom” we’ve set to 2, which is going to make everything we put in our game twice as big. Now our true resolution will fill the size of the window we had created at the beginning. Keep this in mind when making your own games. Your true resolution and your zoom will determine the size of the window you need to create.

Next, we call the setLogoFX function in FlxGame. This controls the appearance of the Flixel Logo that appears when the game first starts. We’re setting the color to white.

super.setLogoFX(0xFFFFFFFF);

Colors in Flixel are usually expressed in this way: “0xAARRGGBB” where “AA” is the “alpha transparency”, “RR” is red, “GG” is green, and “BB” is blue. When the game starts, we want to see the Flixel logo as white on black.

Note For a more in depth explanation of colors in Actionscript, visit this article

13, On the next line, we’ll add the “help” command to tell our players what buttons do what:

help("Jump", "Shoot", "Nothing");

So X = Jump, C = Shoot, and the mouse does nothing for right now.

The help information is all built into FlxGame.as that we are extending. We will not be covering modifying Flixel classes in this doc. Feel free to experiment with them on your own later.

14. Now that we are pretty much done with the Tutorial class, now would be a good time to create the Preloader class. Right click the src folder in the project tree, Create a new class, and name it Preloader. It should look much like the Tutorial file did when it was first created. This time we will import a single specific part of flixel only. Somewhere after the first { and before “public class Preloader”, add a new line and type:

import org.flixel.data.FlxFactory;

This is importing only one specific class from the flixel library, which saves memory from loading unnecessary classes that will not be used for the particular class. Now we need to make this class an extension of the class we just imported, just like we extended Tutorial to FlxGame earlier.

15. To make this class into an extension of FlxFactory, look for the line that says “public class Preloader”. At the end of this line, add on two words:

extends FlxFactory

This will be a very common action throughout this tutorial and when you are making your own games that use Flixel’s library, so remember these steps. Next we need to set this class up to perform its duties.

16. Add these two lines of code to the constructor function within the class:

className = "Tutorial";
super();

This is telling the preloader to gather the files from your game into memory and run the loading screen. Whenever you make your own game, the name of the main class that is set to ALWAYS COMPILE would replace whatever is after className. This is all that needs to be done for the preloader. It is recommended that you keep this file handy for future usage, since it is very easily transferred.

17. We’re almost done with the initial setup. We need to setup our “MenuState” Class next. Add a new folder to the “src” folder, and name it “com”. Within this newly created folder, make one more folder called “Tutorial”. Add a new Class to this folder, and name it “MenuState.as”,

18. Returning to your Tutorial.as file – right underneath your “import”, add a new line and enter:

import com.Tutorial.MenuState;

Understand that the file structure you just created is what you have defined in your import statement. Save everything, and we’re done with this class file!

If you test your project (F5), it should run correctly, and show you the Flixel logo, but then give you an error because we haven’t set up the MenuState file all the way yet.

If you get any other errors before that, check through the steps above and make sure you didn’t miss anything. Once you’ve got it working, move on to the next section!

As of right now, your complete Tutorial.as file should look like this:

 package  
{
    import org.flixel.*;
    import com.Tutorial.MenuState;   

    [SWF(width="640", height="480", backgroundColor="#000000")]
    [Frame(factoryClass="Preloader")]

    public class Tutorial extends FlxGame
    {
        public function Tutorial():void
        {
             super(320, 240, MenuState, 2)
	     super.setLogoFX(0xFFFFFFFF);
             help("Jump", "Shoot", "Nothing");
        }  
    }
}

Back to Contents

III: Creating the Menu

Now that we have your project starting properly, it’s time to move on to making your first State – specifically a FlxState for your main Menu.

Before we jump into creating a state we should first explain what a state is used for. States are Classes that are used primarily as central control points for the different portions of your game. They handle the creation of new drawing surfaces, adding in game objects, changing scores, displaying menus, etc.

In this tutorial we are going to create two basic states. The MenuState, and the PlayState. The MenuState will be used to create a simple menu for the game, and the PlayState will house all of the logic for object creation, score keeping, and collision checking.

Programming Tip:
You can kind of think of States as separate race-tracks that are adjacent to each other. When the player starts the game, they will start on the MenuState track, and they will drive around and around in circles on that track. When we switch to the PlayState, they will teleport over to the PlayState track, which is larger and has more checkpoints and obstacles than the MenuState. When the player dies or quits the game, they get teleported back to the MenuState track, until they want to start playing again. You can have a large number of different states for your game, if you want – you can have a menu state, a load screen state, the game state, an inventory state, etc.

If any of this confuses you, you will feel better once we dig in and start going over the states. If at the end you are still confused, consume the pill that comes with this tutorial, and everything will feel much better.

Back to Contents

The Menu State

1. Since you already created a new class named MenuState earlier, FlashDevelop has created the basic framework for you. Open up this file now, and you’ll see the following:

package com.Tutorial
{   
    public class MenuState
    {
        public function MenuState()
        {

        }
    }
}

2. Like all AS3 classes you will want to define your package and import any classes you will need, so change the first part to look like this:

package com.Tutorial
{
    import org.flixel.*;

3. Next, we want this class to extend FlxState. Remember extending a class that you imported allows you to make a new Class based off of the one you are extending. Change

public class MenuState

to say:

public class MenuState extends FlxState

4. Next, we need to define our Constructor. Now, in this case, because we are using this State as a Menu, we want to ‘take over’ the Constructor function for FlxState entirely. To do this, replace

public function MenuState()
{

with this:

override public function MenuState():void
    {

5. Next, we’re going to display the name of our game on the Menu, with something that tells the player how to start the game. When you have a better grasp of using Sprites, sounds, and special effects, you can put a logo or something else on the menu screen. For now, we’ll just use the FlxText Class. Within the MenuState Constructor, add this code:

	var txt:FlxText
	txt = new FlxText(0, (FlxG.width / 2) - 80, FlxG.width, "Flixel Tutorial Game")
	txt.setFormat(null,16,0xFFFFFFFF,"center")
	this.add(txt);

Lets take a look at what this is doing.

First, we declare a variable to store our FlxText initialization. This is necessary because FlxText has further formatting options that are not part of the constructor. Now, we’re also passing it an object. The “new FlxText()” is going to create a new FlxText object. We’re going to pass it some additional parameters via the setFormat function inside FlxText, and then our new FlxText object is going to be attached to our MenuState.

By looking up the FlxText Class and it’s constructor in the Documentation, we can see what parameters it’s expecting:

public function FlxText (X : Number, Y : Number, Width : uint, Text : String)

We’re passing: 0 ,(FlxG.width/2) – 80 , FlxG.width , and “Flixel Tutorial Game” , which should place our text, “Flixel Tutorial Game”, near the center of the screen.

Next, we’ll look at what setFormat is doing. FlxText’s setFormat function asks for its own parameters in order to set the style:

public function setFormat (Font : String , Size : Number , Color : uint , Alignment : String)

This time we are passing: null , 16 , 0xFFFFFFFF , and “center” . We want to use the default font used within flixel, so we send a “null” value which is essentially saying “don’t change the value”. The text should appear as 16 pixel white text centered. Note that it is 16 “pixels” tall, don’t confuse this with font point size when using your own fonts.

Lastly, “this.add(txt)” is essentially saying "take something and attach it to ‘this’ ". “This” is sort of a shortcut to refer to the current object in AS3. In our case, “This” refers to the instance of MenuState that is currently open and running through this Constructor, and we are telling it to take the current state of our FlxText object “txt” and display it in the position we’ve specified.

6. Lets also tell the player how to start the game. In a new line right under our other text, add:

	txt = new FlxText(0, FlxG.height  -24, FlxG.width, "PRESS X TO START")
	txt.setFormat(null, 8, 0xFFFFFFFF, "center");
	this.add(txt);

This should add the text “PRESS X TO START” near the bottom of the screen in white, and in a smaller pixel size. That’s all we want to do in MenuState’s Constructor.

7. We now need to tell the game what to do each time it ‘updates’. Most programs have some sort of system loop that is always running while the program is running – usually a large number of iterations per second. This loop, in its simplest form, goes something like this:

Start:
wait for something to happen
Go back to start

In our case, Flixel’s game loop is mostly going to be handling a lot of stuff for us, so we won’t have to worry about it, but we do want to be able to do things while this loop is running, so we use the “update” function.

Essentially, Flixel is going to call “update” every loop iteration, and we can choose to have things happen within the update function if we want. For the MenuState, we’re simply going to wait for the Player to press X. Add this code after the Constructor, and before the last “}” in the class:

override public function update():void
{
    if (FlxG.keys.pressed("X"))
    {
        FlxG.flash(0xffffffff, 0.75);
        FlxG.fade(0xff000000, 1, onFade);
    }            
    super.update();
}

We’re adding a whole function at once, but don’t worry, it’s pretty simple.

First, we’re going to “override” the “update” function that’s in FlxState – this means that instead of FlxState’s update being called, we’re saying “use MenuState’s update instead”.

Next, we ask if FlxG.keys.pressed(“X”) is True or not. “FlxG” is a Class in Flixel that handles a lot of general pieces all at once. “keys” is a variable in FlxG that calls the FlxKeyboard class, “pressed” is a boolean function within the Keyboard class that checks if the key we are requesting to be checked (“X”) has been pressed. So, we’re asking “is FlxG.keys.pressed(”X") True?" If it is, for example, the player has pressed the letter X on their keyboard, we’re going to perform the next section of code.

(Note: There are several ways to check if a key has been pressed. “pressed” checks if a key is being pressed this cycle of code. “justpressed” is checking if the key being requested was pressed in the cycle that ran the before the current one. Lastly, there is the boolean variable call of the key you are requesting which runs through the handleKeyDown function, asking if you are holding down the key you are specifying. Keep in mind that all of these require a CAPITAL letter to be typed into the code, as lowercase is not handled.)

Regardless of if keys.pressed(“X”) is true or not, we’re going to call the “super.update()” function, which basically says: "now call the “update” function of whatever class I’m extended from".

So, if X is pressed, and keys.pressed(“X”) is true, then we’re going to do two things.

  • First, we’re going to call the FlxG “flash” function, which is going to flash the color white on the screen, then we’re going to fade to black, via the “fade” function.
  • When the fade is complete (which should take 1 second), we’re going to call the “onFade” function, which we’ll write next.

8. Underneath the constructor, we add a new function:

private function onFade():void
{
      FlxG.switchState(PlayState);
}

This function will be called after the fade command is finished. All it will do is switch the current state from MenuState to PlayState.

9. We can go ahead and create the PlayState file – add a new Class file to your com/Tutorial folder, and name it PlayState.as.

p.So, lets review: when the player starts the game, its going to initialize itself and then enter the MenuState:

  • When the MenuState loads, its going to put the text on the screen and then wait for the player to press X on the keyboard
  • Once the player presses the button, the screen will Flash white, then fade to black.
  • As soon as it finishes fading, it’s going to switch the game’s state from MenuState to PlayState – which will be where all our game logic is.

Make sense?

If you try out your game now, you’ll be able to see the menu come up, and flash/fade when you press X. After that will be an error because we haven’t finished with the PlayState yet… we’ll get to that in the next section.

So your MenuState.as file should look like this:

package com.Tutorial
{
    import org.flixel.*;
    public class MenuState extends FlxState
    {
        override public function MenuState():void
	{
		var txt:FlxText
		txt = new FlxText(0, (FlxG.width / 2) - 80, FlxG.width, "Flixel Tutorial Game")
		txt.setFormat(null,16,0xFFFFFFFF,"center")
		this.add(txt);
			
		txt = new FlxText(0, FlxG.height  -24, FlxG.width, "PRESS X TO START")
		txt.setFormat(null, 8, 0xFFFFFFFF, "center");
		this.add(txt);
        }
        override public function update():void
        {
            if (FlxG.keys.X)
            {
                FlxG.flash(0xffffffff, 0.75);
                FlxG.fade(0xff000000, 1, onFade);
            }
            super.update();
        }
        private function onFade():void
        {
            FlxG.switchState(PlayState);
        }
    }
}

Stay tuned for the next part where we discuss the PlayState, and creating your Sprites!

Back to Contents

Clone this wiki locally