Showing posts with label AS3. Show all posts
Showing posts with label AS3. Show all posts

Saturday, March 31, 2012

Astra Itinera

My first iPad game, Astra Itinera, is now available on iTunes! Astra Itinera is a turn-based strategy game. Check out the Facebook page.

Astra Itinera grew out of my AS3 Strategy Games tutorial series. If you'd like to learn how to create random terrains, use connected component labeling, A* (a-star) pathfinding, state machines and more, check out the tutorial

Recommended by MacMost.com: "The interface is simple, but the game play is deep."

Mentioned in the CartoonSmart.com blog.

Sunday, October 26, 2008

Array Functions in AS3

AS3 Array class has some really handy functions that I never noticed before. They will be very useful (how did I ever NOT notice them?):

every(callback:Function, thisObject:* = null):Boolean
Executes a test function on each item in the array until an item is reached that returns false for the specified function.

filter(callback:Function, thisObject:* = null):Array
Executes a test function on each item in the array and constructs a new array for all items that return true for the specified function.

forEach(callback:Function, thisObject:* = null):void
Executes a function on each item in the array.

map(callback:Function, thisObject:* = null):Array
Executes a function on each item in an array, and constructs a new array of items corresponding to the results of the function on each item in the original array.

some(callback:Function, thisObject:* = null):Boolean
Executes a test function on each item in the array until an item is reached that returns true.

Saturday, July 19, 2008

AS3 vs Java Local Variable Scope

In some languages, you can scope variables within blocks of code, like in different compound statements. For example, the following is legal in Java:
{
int i = 0;
}
{
int i = 1; //Legal in Java
}
But adding those {} to make a compound statement does NOT work in
ActionScript 3 because the AS3 compiler takes all the local variables
(regardless of depth) and declares that right at the beginning of the
function. For example, this is legal in AS3:
    trace(i); // Legal in AS3, default value of int (zero) is output
var i:int = 1;
trace(i);
It appears we're accessing a variable before it is declared. But since the compiler moved our declaration to the beginning of the function, there is no error. The assignment is not moved, the the value of i at that point is zero. This behavior is similar to the way Flash deals with variables
declared later on the timeline, you can reference them before earlier
than the declaration because the compiler moves that declaration to
the beginning.

Friday, July 11, 2008

SWCs and FlashDevelop

I'm thinking my Bits of Blender episodes are really cutting into my blogging time! But I thought I'd put a note out on my latest development approach in FlashDevelop for Flash/ActionScript 3 projects.

Previously, I'd set the main class as the Document class. Then I would set the parent class of Symbols to a corresponding ActionScript 3 class. I'd turn off the automatic declaration of variables so that it would force me to declare them in the class. This was nice because I would have a reminder at the top of the class that there were named instances in the symbol. I'd also add a "//MC" after the declaration as another reminder why I had those members set to "public" (I'd also set "//MC" as one of the tasks so I could quickly find all the named instances on the stage).

But for a recent project, I decided to go with compiling in FlashDevelop instead of Flash. When I'd used FlashDevelop for some Flex work last year, I was always impress with how quickly it compiled. Flash seems to take much longer. I think it may be because FlashDevelop uses the Flex compiler which is doing incremental compiles and Flash is always compiling everything (I'm guessing). So instead of working in Flash, my main Flash class is not running in Flash. Instead, I'm bringing all of my Flash assets in via an SWC. This gives me the advantage of compiling straight in FlashDevelop (and not having it switch to Flash, in fact Flash does not even have to be running). Plus, my compiles are faster. But there is one downside, now instead of my Flash symbol extending an AS3 class, I'm having my AS3 class extend the symbol. This means any named instances in the class are in the symbol instead of in the AS3 class, so I no longer have that reminder of the declaration at the top of the class. The instance is still declared and still appears in the code completion, but it just does not feel quite as good. Overall, though, this approach weighs in feeling like a better way to go.

Sunday, April 13, 2008

Reflection in ActionScript 3

I'm not a big fan of the old eval() function in earlier versions of ActionScript. As of ActionScript 3, it is no longer supported. For the most part, that is a very good thing. My buddy, Jason, is migrating from AS2 to AS3 and he found himself looking for the eval() function. He came to me and asked me about it, I replied "you mean the evil() function?".

The problem with eval() is that you were executing code that was being created at runtime, meaning there's no chance of the complier helping you catch errors. He showed me the code he was working on and --usually-- you can solve the lack of eval() through a better architecture. As I looked at his program, I realized he had a pretty elegant solution. Re-architecting would take a good deal of time and not necessarily yield as elegant result. Java has quite a few classes for dealing with reflection, so I figured (given how similar AS3 is to Java) there must be some similar classes. As it turns out, the pickings are pretty minimal... but there were enough to come up with a nice, dynamic solution to his problem.

In the flash.utils package, there are a number of public functions. The one we were looking for (before we even knew it) was getDefinitionByName(). This function takes a string that is the name of a class, an returns the class object for it. With the class object, you can then create an instance of the class. Here's a simple example you could run in the Flash IDE:
var myClass:Object = getDefinitionByName("Symbol1");
addChild( new myClass() );
It assumes you have a Symbol named "Symbol1" that is exported for ActionScript. If you are doing this in Flex or inside an external class file, remember to import the flash.utils package. The danger of runtime errors still exists, but it is more limited now in that you can create classes and not just execute and arbitrary chunk code on the fly like you could with eval().

Audio Display List?

The Flash 9 player using ActionScript 3 (for Flex or Flash), has an internal structure called a display list. Items in the display list, will be shown, items not in it will not be shown. So if you load an external SWF, it will not be visible until you add it to the display list. Once it is in the display list, it'll receive events (like MouseEvents, KeyboardEvents, ENTER_FRAME, and so on). That's nice, because you can load it and display it at will.

But what about a SWF that also contains audio? As it turns out, there is no audio equivalent to the display list. Once a SWF containing audio is loaded, it will begin to play and you'll hear the audio, whether or not you're displaying it. To stop the audio, listen for Event.INIT on the loaderInfo in the Loader object. Event.INIT fires when the first frame is loaded so you can call stop() it to prevent the playback head from moving forward in the timeline.

Monday, March 10, 2008

FlexBuilder vs FlashDevelop

I've been using both FlexBuilder and FlashDevelop at work lately. I'm a long time FlashDevelop user, so I've a little bias towards it. Lately, I've been trying to look at FlexBuilder with regards to its strengths. I've found that if I am doing a lot of MXML coding, FlexBuilder is a better tool. You have a class view of the MXML and it is good about hinting for MXML attributes. If you need to do absolute positioning, FlexBuilder also wins because of it's WYSIWYG editor.

But when it comes to ActionScript 3 coding, I'd much rather be in FlashDevelop. FlashDevelop's code hinting is much more powerful, for example it does NOT require you to type exactly the right characters. It's a breeze to jump around to declarations of code as well as nice features for creating getters/setters, promoting local variable to member variables, and creating event handlers. The look and feel of FlashDevelop is also nice, it launches and runs quickly. It has good defaults, a user-friendly UI, and good choices for fonts (I guess that could fall under "good defaults"). FlashDevelop is also free.

Monday, December 31, 2007

Buttons, Symbols, and Filters

I just spent another couple hours of my life tracking down a bug in Flash CS3 that turned out to be... drum roll...

If you put a drop shadow on a symbol that is inside of a Button, the movie will freak out without giving any sort of error messages.

Well, at least it wasn't as bad as Friday's LoaderContext problem. Right now I'm also investigating some bizarre behavior with embedded fonts on dynamic fields, more on that when I know more.

Saturday, December 29, 2007

Favorite ActionScript 3 and Flash 9 Books

I was just writing someone about my favorite ActionScript 3 and Flash 9 books and thought it might be worth elaborating on in the blog. These are not all my AS3 books by any means, but they are my favorites. You may also be interested in these if you're doing Flex development. I do have opinions on Flex books, but that's another blog.
  • ActionScript 3.0 Game Programming University - This may be the most fun way to get your feet wet in AS3 and Flash 9 if you're already experienced with Flash. Especially if you prefer to look at complete examples to learn from. You can also use the numerous examples to build upon instead of starting from scratch. Plus, it is Flash-oriented where many of the ActionScript books are Flash-neutral. The book has great support with an accompanying website with demos of the games you can play, as well as a forum to interact with the author and other readers.
  • Foundation Actionscript 3.0 Animation: Making Things Move! - Another fun and great way to learn AS3 programming. This book is Flash neutral, so you can do it from a text editor with the Flex SDK compiler, FlashDevelop, FlexBuilder, or Flash. While his examples are not complete games like the above, they are small, useful examples. He also gives a good intro to AS3.
  • Essential ActionScript 3.0 - If you plan to write AS3 code, this book is a must to have.
  • Flash CS3 Professional Advanced - This is a great intro to Flash 9 with AS3, probably my favorite all-purpose Flash book, I review it here. This book will effectively bridge your Flash 8 and AS2 knowledge to Flash 9 and AS3. It has very clear explanations and illustrations.

Tuesday, October 09, 2007

Interacting with Flex in Flash

I was trying to bring a Flex 2 SWF into Flash CS3 and interact with it. I was able to load the Flex swf without a problem but when I tried to access a public property or function I'd get the following error:

ReferenceError: Error #1069: Property hello not found on
_Main_mx_managers_SystemManager and there is no default value.

So I did the natural thing and Googled it before spending time figuring it out :)
Unfortunately, my search came up empty :(

Looking into the docs class mx.managers.SystemManager gave me the clue I needed. To get at the actual application, I needed to get to the first child of the loaded content. The compiler was unhappy with calling getChildAt() on the content object, so I cast it into an Object along the lines:

var flexApp:Object = (loader.content as Object).getChildAt(0);
trace(flexApp.hello);

That did the trick!

Wednesday, September 19, 2007

Populating a TextField before it exists

A friend of mine posted the following Flash problem the other day:

I tell a movie clip to go to a frame. I want to put something in text fields on that frame, or set some property of some movie clip on that frame. But if I gotoAndStop, and then on the next line of AS try to set something, I get an error. I need to wait for the frame to start, or the objects on the frame don't exist yet. So I have to put a function call on the frame to call a second function to do the setting later on.

The is quite messy. Surely there has to be a better way.

I came up with the following solution, which I think is fairly elegant. You make a symbol with a TextField in it. Set the symbol to extend from a class which has a public static variable you can set, then when the symbol is instantiated later it uses that class variable in the constructor. This works because the class is loaded when you reference it, it doesn't matter that an instance of the class does not yet exist.

The static variable could be an object so you can better identify what value should be populated. You can get the instance name in the constructor to determine which property of the object in the class variable to use. Here's an example of the class:
package {
import flash.display.MovieClip;
import flash.text.TextField;
public class JRNTextField extends MovieClip{
// should use a getter/setter
public static var mytext:Object = new Object();
public function JRNTextField(){
textInSym.text = JRNTextField.mytext[this.name];
}
}
}

In frame 1:
JRNTextField.mytext.asdf = "hello";
JRNTextField.mytext.qwer = "goodbye";
In frame 2:
stop();

Frame 2 has two instances in the timeline of a symbol that extends the JRNTextField class.

The symbol contains a dynamic TextField that is named "textInSym".

The instances on frame 2 are named "asdf" and "qwer". As hoped, they get
populated with "hello" and "goodbye", respectively.

Saturday, September 08, 2007

Code-behind and States in Flex 2

I've always liked the .NET way of developing web pages, where you have your code separated from your layout. Someone just referred me to this post on using Flex in a .NET code-behind style (thanks Steve!). It's very similar to .NET, you just extend the Application class and use it in your MXML file.

It is very cool but there's a minor error where the package name is left off the screenshot (though the instructions are correct). One of the comments on the post noted that in order to use states with this approach you needed to make a small change from "mx.states" to "app.states" where "app" is the namespace of your application.

I thought I'd post a version of this approach that included the states issue. I hilited where you need to change "mx" to "app" and where you need to add "app" as the namespace. The shots below are of code done in FlashDevelop 3 (beta 3).


UPDATE: September 14, 2007 1:07 PM I've had additional troubles with using the code-behind and states. I'm afraid for now it's best to hold off on using the approach.


Sunday, September 02, 2007

Drawing Limit on Sprites

I learning something new this weekend. When drawing on a Sprite in ActionScript 3, I assumed you were just drawing on it like you would a graphics port and the result was just changed pixels in memory. Ah, but after some pain (and a SWF freezing at exactly the same time each time I ran it) I found it keeps track of the number of things you've drawn on it.

How many items does it keep track of? The nice computer-y number 65536, aka 2^16 or 0x00FFFF. Before you reach that limit you should call the clear() function of the graphics object of your sprite, ie:
   mySprite.graphics.clear();
But now with that past, I've got the beginnings of a nice 2d terrain generator.

Saturday, September 01, 2007

MovieClip Identifiers

Here's something interesting I found in Flash CS3 using ActionScript 3. Say you have the following:

Frame 1:
trace(this.hasOwnProperty("my_mc");
trace(my_mc);

Frame 2:
A MovieClip instance named "my_mc"
trace(this.hasOwnProperty("my_mc"));
trace(my_mc);

The output is:
true
null
true
[object MovieClip]

So Flash assigns the property identifier "my_mc" to the current timeline's instance at the start of the movie, before the actual instance occurs on the stage. Then when it does, that property is populated with a reference to the instance. I assume the identifier is created at compile time.

Thursday, August 23, 2007

Getting back the hand cursor in AS3

As I migrate from Flash ActionScript 2 (AS2) to ActionScript 3 (AS3), I'm always finding little differences. In AS2, if you set the onPress event of a MovieClip to a value, your MovieClip will then cause the cursor to switch to the hand cursor when you mose over it. I found in AS3, you need to manually set two properties to get this effect (thanks Colin!):
myClip_mc.buttonMode = true;
myClip_mc.useHandCursor = true;
That's kind of a drag if you have already created a movie with dozens (or more!) of clickable MovieClip instances. I'd done just that so I was hoping I was missing some global way getting back this functionality easily. There wasn't... so I made one :)

Below is a class that extends from MovieClip, and in its constructor it sets the two properties I'm looking to be set:
package {
import flash.display.MovieClip;
class ClickableMovieClip extends MovieClip {
function ClickableMovieClip():void {
this.buttonMode = true;
this.useHandCursor = true;
}
}
}
So all I had to do was go into my library and set the Base Class of each of the Symbols I knew I wanted clickable in my movie. One weird thing I found: after typing that in to the base class field, I needed to click the check mark next to it, it you just clicked "OK" then it'd give you an error.

Sunday, August 05, 2007

FlashDevelop 3.0 Beta

Yes this has been the weekend of Flash technology...

I've been messing with ActionScript 3 today as I read through Essential ActionScript 3.0 and Programming Flex 2. Being one to be easily distracted by shiny objects, I found a shiny object. FlashDevelop 3.0 is in beta and it works pretty nicely. I'd messed with FlashDevelop 2.0 but hadn't used it in quite a few months. I downloaded 3.0 tonight and it works great with Flash CS3! You can create a Flash IDE project from a template. It works better than the Flash code editor (so did the previous version). It makes coming up to speed on the new APIs much easier.

Flex 2 States

I've been learning a little about Flex 2 this weekend while working through O'Reilly's Programming Flex 2 by Chafic Kazoun and Joey Lott. There's always a big gap between working through a book and doing a real project when it comes to technology.

That said, one feature of Flex 2 that I think is implemented quite well is states. From my practice, it seems Adobe has implemented the concept in a straightforward manner. States relate to the view. You create different states for different modes your program is in. A program can only have one current state at a time. I'm impressed at how easy it is to set up a series of states and switch between them. When you do switch between states, the different controls on a state preserves its own state, i.e. a checked CheckBox remains checked whether it is part of the active state or not. I look forward to seeing whether I feel the same in actual practice.

Saturday, August 04, 2007

ActionScript 3.0

I'm finally able to begin getting into ActionScript 3.0 (AS3). As I do, I'm amazed at the Java influence (with some C#).

Funny thing. My first AS3 project started as a very simple click a MovieClip and go to the next frame. No surprises there, right? LOL!

My simple:

stop();
trading.onPress = function(){
this.play();
};
Became:
stop();
function nextScreen(event:MouseEvent):void{
this.play();
}
trading.addEventListener(MouseEvent.CLICK, nextScreen);
trading.buttonMode = true;

While not that much more syntactically, definitely different and a big jump towards the Java way. Having taught Java for two years, I don't mind it. But I am curious how other folks will like it.

This was enough of a change to make me pick up O'Reilly's Essential ActionScript 3.0 by Colin Moock. It's funny that the title says "Essential" and the subtitle is "ActionScript 3.0 Programming Fundamentals". Why is it funny? The book is around 900 pages, and it is not large print. Colin does his usual job of superb thoroughness in covering the topic. If you're working with AS3, it's a must have.