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.
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.
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.
I didn’t really have to play Twilight Princess. I’d already attempted to play through the game twice — once on a friend’s Wii (he moved out and took my save with him), and once on my own (I got bored with the slow, tedious pace of the start of the game). Normally, two false starts would be enough for me to realize that a game probably wasn’t good enough to play through. This time was different. For whatever reason, even though I had a better game to play, I felt a strange, compelling desire to finish Twilight Princess. It’s not as if I’ve beaten all the previous Zelda games, and therefore had to finish this one to put a notch in my controller; I never finished Wind Waker, or the GameBoy Color iterations. My feelings were unquantifiable.
Anyway, for whatever reason, I did play it. I don’t particularly regret playing. Zelda is Zelda, after all. Whatever faults a Zelda title may have, it’s still been put together by one of the most talented game development groups in existence. The puzzles are sometimes clever, there’s enough new content to feel like you’re doing something new, and the nostalgia that Link evokes are enough to carry the player through.
Twilight Princess had enough to carry me through, but just barely. There’s not a lot of really new things in the game. The art direction is a weird mashup between Zelda 64 and Shadow of the Colossus. The geography in the game is all rehashed. There’s a dark, alternate world that alters your physical form. The few actual new items are kind of lame: you use them a couple times, and then forget about them. The antagonist turns out to be a puppet for Gannon (surprise!). The game is not difficult at all; even in boss fights, there are breakable jars all over the room that supply you with hearts up the wazoo.
There’s a lot of “extra” stuff packed into the game, but I never felt compelled to get 100% of the items. It’s mostly there just for it to be there, not because it adds any sort of fun. This time around, it takes five pieces of heart to get a heart container, instead of four. Why? Just for more tedious collection, I guess. You can collect fish, bugs, ghost souls, and who knows what else. I don’t even have to resist my OCD tendencies to ignore this stuff; it’s just filler content.
What kept me going? The idea of Zelda, I guess. The memories of how fun the other games in the series are. I transposed the fun I had with other titles to what I was currently playing. That and my natural gamer’s desire to finish the game, just to be able to say I finished it. It’s like reading a long, boring classic. I don’t know if the experience itself made me better, but it’s done with, and I never have to do it again.
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.
One of the big downsides about not using the Flash IDE for development is that it’s much more of a hassle to bring graphics into your program. The IDE has a built in vector illustration program, which allows the user to create graphical objects (or import them from Illustrator) and link them right up to a corresponding Actionscript object. If you’re making programs with the Flex SDK, however, getting graphics is a bit more of a chore. Fortunately, it’s not nearly as difficult as programming graphics via Actionscript.
First, you’ll want to get a vector illustration program. Adobe makes Illustrator, which might be your first thought, but we’re trying to do things on the cheap here, otherwise we’d just get the Flash IDE. Inkscape is a free program which can save files in the SVG (scalable vector graphics) format. Grab a copy of Inkscape, and fire it up (OS X users prior to 10.5 will need to install X11).
Inkscape starts up by creating a default document, which is much larger than anything we would normally use. From the ‘File’ menu, navigate to the ‘New 32×32 Icon’ option. Now, in the smaller image, use the ‘Circle’ tool to create a circle. Take some time here to play around with Inkscape: experiment with changing the color of the circle, give it a border, do whatever you like. When you’re satisfied with what you have, click ‘Save’ and save the image as a ‘Plain SVG.’ Now, create a new Actionscript file in the same directory as the graphic file called ‘SVGExample.as’, and enter the following code:
package {
import flash.display.Sprite;
public class SVGExample extends Sprite {
[Embed(source="ball.svg")]
public var BallGraphic:Class;
public function SVGExample():void
{
var b:Sprite = new BallGraphic();
b.x = 100;
b.y = 100;
addChild(b);
}
}
}
The way that graphics are embedded is as follows: first, you use the ‘Embed’ syntax to specify where the image is, and then you link that embedded asset to a unique class name. Here, I call it “BallGraphic,” but you can use anything that makes sense to you. Creating an instance of that class (when I call new BallGraphic()) loads the graphic, and it can then be added to a display object container and shown on the screen. When you compile this code and run the SWF, you should see your graphic on the stage. You can now easily import SVG graphics (or even other image types, such as .gif/.jpg) via Actionscript.
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.
What with Thanksgiving and having to teach my Bible study last week, I haven’t had a whole lot of time for programming recently. Couple that with the fact that I’m psuedo-sick again, and it’s hard times for Actionscript. I needed some inspiration this past weekend, which I got in the form of browsing around some stuff the indie community is doing. Also, by firing up my Aquaria demo (which I never finished).
Anyway, check out the most recent build. I got some simple “alien” type guys moving around in there, and am experimenting with a background. I’d like to try making the background move in relation to the ship, but I’m not sure how the effect will turn out. Guess we’ll see!
A while ago I discovered a reproduction of the famous 1990 NES World Championship cart being sold by some chaps called RetroZone. It’s basically a collection of three games, Super Mario Bros., Rad Racer, and Tetris, with a built-in 6 minute timer. Collect coins in Mario, go the distance in Rad Racer, and get yo’self some lines in Tetris… then check your score. I would have loved to have actually played this original cartridge 18 years ago, but my family lived too far away from any of the major metropolitan areas that the World Championship tour went to. There was no way I could have convinced my parents to drive to Denver (the nearest city) for what would be essentially a 6 minute gameplay session (plus a few hours waiting around, I’m sure). If you have some cash, and want to experience some nostalgia, hit up RetroZone to purchase a copy of their reproduction. It’s a much cheaper way to play the experience without paying the $5k+ that the real carts are being sold for.
So, although Flash/Actionscript has super easy ways to scale and rotate a graphical object, when I loaded up a PNG for my spaceship and tried rotating it, it looked pretty ugly. Of course, I didn’t expect OpenGL-quality scaling and rotation, but I was surprised at how bad it looked. I soon learned that while you can easily import bitmap graphics into Flash (i.e. GIF, JPG, PNG) they don’t keep their quality if you scale or rotate them. In order to do that, you need to use vector graphics. The gist of vector vs. bitmap graphics is that bitmaps are based on pixels, which do not scale very well, while vector graphics are based on mathematical equations that can be scaled based on screen/size requirements.
One benefit of the Flash IDE is that you can easily create vector graphics and use them in your movie/program. In my initial research, it wasn’t immediately apparent if you could create vector graphics in another program and then import to Flash. Of course, you can do it with Adobe Illustrator, but how about some other (free) program?
Turns out that you can. Inkscape is a free vector graphics editor, which can output SVG file format images that can be directly imported via Actionscript into your Flash program. Pretty great! One of my goals for today is to learn the basics of a vector graphics editor… I’m fairly familiar with programs like Photoship/GIMP, but Inkscape seems to have some different paradigms that I’ll have to pick up.


Recent Comments