wonderfl

This isn’t exactly news, but I created an account on the Japanese social network/code sharing site Wonderfl. It’s kind of cool… you can use the site to automatically compile Actionscript 3 code, then save it for other people to check out. If you see some code you like, or that sparks a new idea, you can “fork” it — copy it and save your own version. I was kind of surprised… I added two small demos on Monday, and by Wednesday some other users had already modified my demos. There’s a lot of random crap, but you can also learn some cool techniques by browsing through the user-submitted code. If you have any interest in Actionscript, you should check it out.

No comments · Written by Nathan at 1:28 pm · Tags , , , ,


Animation in Actionscript 3

I think one of the main disadvantages of using the Flex compiler to create Flash programs is that animation is a bit more difficult to create (although, to tell the truth, I’ve never used the Flash IDE enough to be able to compare them). I think for most simple games, you can get away with not animating any of your characters. But once you get into creating games that have more detailed characters, you pretty much need to add some sort of animation. We can do that pretty easily by loading multiple images into a DisplayObjectContainer (such as a Sprite) and then showing/hiding each image in turn. Take a look at the following example:

package {
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.utils.getTimer;	// for getTimer()

  // Set SWF FPS, etc.
  [SWF(frameRate='30', width='200', height='200', backgroundColor='0xffffff')]

  public class AnimationExample extends Sprite {

    // For frame rate info
    public var ticks:Number = 0;
    public var framesPerSecond:Number;
    public var frameTimer:Number = 0;
    public var currentAnimationFrame:int = 0;

    // For animation
    [Embed(source="run-1.svg")]
    public var animationFrame1:Class;
    [Embed(source="run-2.svg")]
    public var animationFrame2:Class;
    [Embed(source="run-3.svg")]
    public var animationFrame3:Class;

    public var character:Sprite;

    public function AnimationExample():void {

      // Create new sprite for animation frames
      character = new Sprite();

      // Add frames, hide all but the first one
      character.addChild(new animationFrame1());
      character.addChild(new animationFrame2());
      character.addChild(new animationFrame3());
      character.getChildAt(1).visible = false;
      character.getChildAt(2).visible = false;

      this.addChild(character);

      // This will call the animation function
      this.addEventListener(Event.ENTER_FRAME, enterFrame);
    }

    public function enterFrame(e:Event = null):void {
      // getTimer() provides # of ms since Flash Player started
      var currentTicks:Number = getTimer();

      // Figure out how many seconds each frame is displaying for
      var secondsPerFrame:Number = (currentTicks - ticks) / 1000;

      // For the heck of it, you can also determine FPS
      framesPerSecond = 1 / secondsPerFrame;

      // Set this var for the next iteration
      ticks = currentTicks;

      // Increment the timer
      frameTimer += secondsPerFrame;

      // Compare the frameTimer value against the number of seconds you want each frame to display
      if(frameTimer > 0.5) {
        // Reset the frame timer
        frameTimer = 0;

        // Hide the first frame
        this.character.getChildAt(0).visible = false;

        // Move the last frame up to be first
        this.character.setChildIndex(this.character.getChildAt(2), 0);

        // Show the new first frame
        this.character.getChildAt(0).visible = true;
      }
    }
  }
}

Download the code, .swf, and (bad) graphics.

In addition to the setChildIndex() function that swaps the depth of each animation frame, there’s also some code that obtains the current frame rate, which helps set the speed of the animation. In some games, the motion of all the characters can be limited by a number derived by the frame rate, which helps ensure that the game runs the same speed on different computers. This isn’t totally necessary in Flash, however, since it’s possible to limit frame rate by using [SWF(frameRate='XX')] at the beginning of your Actionscript package.

No comments · Written by Nathan at 12:21 pm · Tags , ,


Compiling Papervision3D projects
using mxmlc

There’s a new competition going on at TIGsource called the “Cockpit Compo,” wherein the design constraint is using a cockpit (or similar HUD). I doubt that I will have time to actually make an entry, but since I’m using Actionscript/Flash as my language/platform of choice now-a-days, I’m trying to look into a 3D library for Actionscript. Papervision3D seems like a favorite, so my next step is to find some tutorials and give ‘em a shot. First, though, we have to figure out how to actually compile projects with Papervision.

1. Obtain the (free) Flex SDK, and put it somewhere in your system path. I wrote a post about setting up your Actionscript development environment; check it out if you haven’t done this already.
2. Download the Papervision3D compiled library (.swc) or source (.as). It doesn’t really matter which one, as I will explain how to use ‘em both.
3a. If you got the .swc, put it in the same directory as your project files and rename it to ‘papervision3d.swc’. When you compile, add the flag -include-libraries papervision3d.swc. That’s it!
3b. If you got the .as source, extract it and put the ‘/org’ directory in the same directory as your project files. Compile as normal, you don’t need to feed mxmlc any extra flags.

To test out the process, get the “Simple HelloWorld Example for Papervision3D 2.0″ .zip that’s on the Papervision3D downloads page. Drop in the .swc or the /org directory (depending on what you downloaded), then compile using the instructions above. I got the .swc, put it in a subdirectory called ‘/libs’ within the /src, and compiled with mxmlc Main.as -include-libraries libs/papervision3d.swc. If everything goes the way it should, a .swf will be produced that displays a crazily-textured spinning sphere.

1 comment · Written by Nathan at 2:39 pm · Tags , , ,


Add an Event Listener in Actionscript 3

Importing graphics into your Flash program is all well and good. You can create movies or animation, but the real interesting thing is taking user input and having your program react to it. The way to do that in Actionscript is to add “Event Listeners” to objects you create. Whenever an event occurs (such as a keypress, mouse movement, or whatever), your Event Listener checks to see if it’s supposed to do anything. If so, then it runs a function with code that you specify. So for example, say the user presses the “left arrow” key. Your keyboard input event handler sees this, and runs appropriate code (in this case, it might move a game character left).

One of the most basic events in Actionscript is the “enter frame” event. This triggers every time the SWF is redrawn, and basically corresponds to the SWF frame rate. In the following example, we’re going to create a new class, and add an “enter frame” event listener to it, so that whenever a new instance of that class is created, a function will run at frame rate.

package {
  import flash.display.Sprite;
  import flash.events.Event;  // Required to add event listeners

  // Set our SWF framerate, width, height, and background color
  [SWF(frameRate='30', width='640', height='480', backgroundColor='0xffffff')]

  public class EventListenerExample extends Sprite {

    [Embed(source="ball.svg")]
    public var BallGraphic:Class;

      // Variables used to store movement data
      private var dx:int = 5;
      private var dy:int = 5;

    public function EventListenerExample():void
    {
      // Create instance of imported graphic
      var b:Sprite = new BallGraphic();

      // Add to this display object
      this.addChild(b);

      // Attach event listener
      // Listen for "ENTER_FRAME" event
      // Run the "enterFrame" function
      this.addEventListener(Event.ENTER_FRAME, enterFrame);
    }

	public function enterFrame(e:Event):void
	{
	  // Increment position
	  this.x += this.dx;
	  this.y += this.dy;

	  // If object passes beyond SWF boundaries,
	  // reverse direction
	  if(this.x >= 640 - this.width || this.x <= 0)
	    this.dx *= -1;
	  if(this.y >= 480 - this.height || this.y <= 0)
	    this.dy *= -1;
	}
  }
}

Save this code in a file named ‘EventListenerExample.as’. You can see that we’ve elaborated a bit on our last example, importing and displaying an SVG graphic. However, this time we add some variables to the class that represent speed (delta-x and delta-y). We attach the event listener by calling this.addEventListener (Event.ENTER_FRAME, enterFrame);. The first argument is the type of event the listener is triggered by, and the second is the name of the function to run when the event is detected.

In the declaration of the ‘enterFrame’ function, we pass it details of the event that triggered it by putting e:Event in the arguments list. The function doesn’t actually use that information, but simply moves our graphic around, bouncing off the “walls” of the SWF. Movement is just one possible application of the ‘enter frame’ event; collision detection can also be calculated this way, among other things.

No comments · Written by Nathan at 2:32 pm · Tags , , ,


How to create Flash programs with
Actionscript 3 and the Flex SDK

So, something I’ve been devoting a bit of my time to recently is learning Actionscript programming. It’s something that I’ve been interested in for a while, but never pursued — mainly because the Flash authoring program (currently CS4) runs around $700 for the full version. Now, if I was a professional, and worked with Flash for a living, I’d have no qualms about dropping that cash. However, it’s a steep point of entry for a hobbyist.

In a bid to make the Flash platform more of an application environment, Adobe has been promoting a new way to author Flash content, called Flex. Flex uses a mix of XML (for layout) and Actionscript (for logic) to more easily create “application-like” programs. Flex is really targeted at the programmer — development is done through a text editor-based environment (although Adobe has made a Flex Builder program to facilitate UI layout). Now, the benefit here is that while Adobe charges for the premium development environment, the actual XML/Actionscript compiler is available for free. This means that you can create pure-Actionscript programs (read: games) for free!

I’m going to quickly show you how to set up a development environment for Flash authoring with the Flex 3 SDK. The first step is to download the SDK. Click the “I Agree” checkbox, and save the .zip somewhere on your computer. It’s a bit large, weighing in at around 120 megs. Extract the files somewhere when it’s finished downloading (c:\flex3 on Windows or /Users/yourusername/flex3 on OS X).

You’ve got the tools, now you need to know how to use them. I primarily use some sort of terminal to do my compiling. For Windows, I recommend Cygwin. OS X users can simply use their Terminal.app program. You’ll have to let your terminal know where your Flex compiler is, so you don’t have to type the absolute path each time you want to run it (i.e. so we can type ‘mxmlc Myprogram.as’ instead of ‘/Home/yourusername/flex3/bin/mxmlc Myprogram.as’). So we’ll add the ‘flex3/bin’ directory to our system path. Here are instructions for Windows and OS X. You’ll want to add the ‘c:\flex3\bin’ directory (Windows) or ‘/Users/yourusername/flex3/bin’ (OS X) (or wherever you put the Flex SDK files) to your path. Once you’ve done that, fire up your terminal and type ‘mxmlc -help’. If you see a bunch of info about the compiler, then you’re good to go.

Next, we’re ready to create a simple program to demonstrate how to author Flash content using only Actionscript. Open up your favorite text editor (my preference is TextMate) and create a file called ‘HelloWorld.as’, and slap this code into it:

package
{
	import flash.display.Sprite;
	import flash.text.TextField;

	public class HelloWorld extends Sprite
	{
		public function HelloWorld():void
		{
		// Create a new variable to hold a "TextField" and assign an instance of the TextField class to it
		var myMessage:TextField = new TextField();

		// Add some text to the TextField object
		myMessage.text = "Hello World!";

		// Add the text to the main display container
		addChild(myMessage);
		}
	}
}

Save your file, then compile it by typing ‘mxmlc HelloWorld.as’. If you see any errors, make sure you copy/pasted the above code exactly. The compiler should output a SWF binary file called ‘HelloWorld.swf’. Double-click it or drag it to your browser to start your new program, and you should see a window with the text “Hello World” displayed in the upper left corner. Congratulations! You’ve successfully set up a development environment, and are now ready to start learning Actionscript and making your own programs.

1 comment · Written by Nathan at 9:34 am · Tags , ,


Older Posts →