Skip to content

Seifer Tim's Tutorial

Rybar edited this page Sep 13, 2010 · 38 revisions

Flixel Basic Game Tutorial

by SeiferTim & DarthLupi

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 demonstrate 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.

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

  • A computer ( or a very fast abacus )
  • FlashDevelop installed and configured
  • Image-editing software that can export PNGs.
  • Some understanding of programming concepts and practices.

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.

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.

    You are going to want to replace package with package com.Tutorial to define the directory structure for the package.

    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 file is basically making all of it’s contents available to the rest of your program. I this case we use the * which loads everything 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 here. This is not the true resolution. This is set later. Think of this as the window size.


  9. Next, we’ll create a preloader. Right click the src folder in the project tree, Create a new class, and name it Preloader. Then type or copy the code below into it:
    package
    {
    	import org.flixel.data.FlxFactory;
    	public class Preloader extends FlxFactory
    	{
    		public function Preloader()
    		{
    			className = "Tutorial";
    			super();
    		}
    	}
    }

  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.
    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, the 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, and if 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.


  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.


  12. 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(). What super() does, without and 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 this line of code:

    super(320,420,MenuState,2,0xff000000,true,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, BGColor : Number, ShowFlixelLogo : Boolean, FlixelColor : Number, FlixelSound : Class, Frame : Class, ScreenOffsetX : uint, ScreenOffsetY : 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.

    “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. “BGColor” is the background color of our game. We set it to black. 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. Next, “ShowFlixelLogo” is set to “true”, and the “FlixelColor” is set to white. When the game starts, we want to see the Flixel logo as white on black. The other parameters are optional, so we’re not going to pass them.

    (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. 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 “Tutorial”. Add a new Class to this folder, and name is “MenuState.as”, and then, in your Tutorial.as file – right underneath your “import”, add a new line and enter:
    import Tutorial.MenuState;

    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 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,0xff000000,true,0xffffffff);
                help("Jump", "Shoot", "Nothing");
            }  
        }
    }

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 we will use 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 obsticles 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.

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 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 Tutorial
          {
              import org.flixel.*;

  3. Next, we want this class to extend FlxState. Remember extending a class that you imported allows your 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:
    this.add(new FlxText(0,(FlxG.width/2) - 80, FlxG.width, 80, "Flixel Tutorial Game", 0xffffffff, null, 16,"center")) as FlxText;

    Lets take a look at what this is doing.

    First, “this.add()” 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.

    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 parameters, 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:

    function FlxText (X : Number, Y : Number, Width : uint, Height : uint, Text : String, Color : uint, Font : String, Size : uint, Justification : String, Angle : Number)

    We’re passing: 0,(FlxG.width/2) – 80, FlxG.width, 80, “Flixel Tutorial Game”, 0xffffffff, null, 16,“center”, which should place our text, “Flixel Tutorial Game”, in white, at the center of the screen (roughly).


  6. Lets also tell the player how to start the game. In a new line right under our other text, add:
    this.add(new FlxText(0, FlxG.height  -24, FlxG.width, 8, "PRESS X TO START", 0xffffffff, null, 8, "center"));

    This should add the text “PRESS X TO START” near the bottom of the screen in white, and in a smaller point 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.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 FlxSprite – this means that instead of FlxSprite’s update being called, we’re saying “use MenuSprite’s update instead”.

    Next, we ask if FlxG.keys.X is True or not. FlxG is Class in Flixel that handles a lot of general pieces all at once. keys is a variable in FlxG that calls the FlxKeyboard class, and X is the keypress we’re checking for. So, we’re asking “is FlxG.keys.X True?” if it is, ie, the player has pressed the letter X on their keyboard, we’re going to perform the next section of code.

    Regardless of if keys.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.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 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 the A button (X on the keyboard).
    • Once the player presses the button, it 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 Tutorial
    {
        import org.flixel.*;
        public class MenuState extends FlxState
        {
            override public function MenuState():void
            {
                this.add(new FlxText(0, (FlxG.width / 2) - 80, FlxG.width, 80, "Flixel Tutorial Game", 0xffffffff, null, 16, "center")) as FlxText;
                this.add(new FlxText(0, FlxG.height  -24, FlxG.width, 8, "PRESS X TO START", 0xffffffff, null, 8, "center"));
            }
            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);
            }
        }
    }
  10. Stay tuned for the next part where we discuss the PlayState, and creating your Sprites!