This blog has moved to a new location! http://iqandreas.github.com/
Showing posts with label ActionScript. Show all posts
Showing posts with label ActionScript. Show all posts

Tuesday, January 17, 2012

Ubuntu: Adding FDT to the list of Applications

This post can be found on the new blog at Ubuntu: Adding FDT to the List of Applications
In this guide, we will add FDT to the list of installed applications, and optionally, install a script which "resets" the internal SWFViewer in case it won't open after closing improperly.




The following guide was written for 32bit FDT5, but may still work for future or previous versions of FDT. These instructions can of course also be used for any application that doesn't come with an Ubuntu installer, adjusting the  files appropriately.

If you are running Ubuntu, I'm assuming you already know how to use the basics of the command line and how to manipulate (create, delete, change permissions) of files. If anyone wants more details, post a comment and I'll clarify.

I'm assuming you have already downloaded FDT (they have a free version if you aren't already using FDT) and extracted the archive.

I would recommend saving the files to /opt/fdt5 (may require admin access, which is easily done without messing with the command line by running  gksu nautilus , assuming you are still using the default file browser) Depending on what extraction tool you use, you may also need to change the permission settings for the files to allow access for all users.

Download the FDT5 Launcher files

If you want to do this the easy way, download the pre-made files from the GitHub repository and install them to the locations specified in the README.
https://github.com/IQAndreas/FDT-Ubuntu-Launcher-Files/zipball/master

You are all done. Enjoy!

Alternatively, you can do all the dirty work yourself (if so, keep reading).

Creating the FDT5 Launcher Files manually

Create a new file named FDT5.desktop with the following contents:


If you want the file to be available to all users of the computer, save the file in /usr/share/applications/
Alternatively, if you only want the currently logged in user to have FDT show up in the application menu, save the file to ~/.local/share/applications/

Next, create the following script, and save it as /usr/bin/fdt5


Note that the script may be a tad more complicated than it needs to be, but this is the script I'm using since I had to jump through a few hoops getting FDT to work properly in Ubuntu.


You also need to set the icon for the application. The default Eclipse icon is okay, but on my system, both Eclipse for Java and FB4Linux use that same icon, so I would prefer being able to tell them apart.

I included FDT's fancy, blue dodecahedron icon in the repository, used with permission from Powerflasher GmbH. You can use the icon provided in the repository, or use your own, but which ever icon you use for FDT, make sure to save it to /opt/fdt5/fdt-icon.png

Finally, if you want FDT to stay in the launcher bar, start up FDT, right-click the icon in the launcher, and make sure "Keep in Launcher" is checked.



Cleaning the SWFViewer settings

If the built in FDT SWFViewer quits improperly (which happens from time to time when running into AS3 errors) it will not open the next time you run the SWF. The solution is to delete a few config files for the plugin, which is a simple task, but gets annoying when you need to constantly delete the files.

The following script will delete said config files (assuming FDT is installed to /opt/fdt5 as recommended) though I wish FDT had a button for this inside the IDE instead.


Save the script to /usr/bin/fdt5-clean and run it by typing fdt5-clean into the command prompt. The script does not require admin rights to run as long as your FDT install folder has full permission for all users.


Leave any further questions or problems in the comments and I'll try to help sort them out.

What Beginners need to know about Performance and Garbage Collection

Another category of beginner questions that often appear on the Kirupa forums are about performance and garbage collection. Some common concerns:
  • How do I make sure my MovieClips are garbage collected? Is setting everything to null enough?
  • Should I always remove all my event listeners?
  • Someone told me it's better to use int instead of uint because it's more efficient.
  • I used "while(--i)" instead, because it is much more efficient than for loops.
  • hitTest() is really slow! Every site tells me I should never use it.
My answer to all those questions: Don't worry about it.


Don't get me wrong, if you are the type of person who worries about these sorts of things right now, you will make a terrific developer one day! But worrying about these things now is just going to make your code more complicated and much more difficult to manage.

Strive to make your code clear and readable

As a beginner, this should be your first and foremost rule. If you scratch your head every time you read your own code, coding will be overwhelming and debugging will be hell.

Take these two identical chunks of code as an example:


The first chunk of code is much more efficient than the second, but I wouldn't want to be the developer that find bugs in that project.

So should I never worry about performance?

Not at this point, no. First make sure you have learned the basics and syntax of ActionScript.
Then, make sure you really know the basics of ActionScript (instead of just thinking that you do while perched on top of mount stupid. Believe me, we have all been there). Finally you can start learning about standard coding conventions and basic performance improvements.

Keep in mind, most performance optimization tips (such as using int instead of uint) will shave milliseconds off your total time if you do tens of thousands of calculations each frame.

Often times, the extra milliseconds won't make a hill of beans difference, so worrying about them while writing the code is a waste of resources. Test your code, and make sure your project works. Then, if (and only if!) there is a problem with performance after everything is complete and working, you can go back and find which areas need optimizing.


Why Garbage Collection doesn't matter

Same principle as with optimization, don't worry too much about garbage collection unless you are building an enterprise-level application. Flash is actually pretty good at taking care of things for you and making sure everything gets disposed of properly. Even if it misses an image here or there, what is one measly Bitmap for a computer with +2GB of RAM? Users won't notice the difference if your game uses 17 MB instead of 16 MB.

And remember, it's all disposed once you close the SWF anyway.

Monday, December 26, 2011

The Humble AIR Bundle

This post can be found on the new blog at The Humble AIR Bundle
I'd like to say straight off the bat that this bundle does not exist. It's just an idea I have been playing with in my mind.

Adobe recently announced that they will no longer be releasing updates for AIR for Linux. This saddens me, mainly because the reason I switched from working with .Net to Flash was the "multi-platformness" - the ability to compile once and have your game or application run on any operating system (it has a proper name, but it's still on the tip of my tongue).

A few games in previous Humble Indie Bundles were actually Flash games (even if the players don't notice it); Samorost 2, Machinarium, and Trauma. Even though Flash can't make the most powerful of games, it's fairly obvious that Flash games are at least playable.

AIR increases the functionality of Flash, and adds mobile devices to the available platforms, all with very little additional changes made to your existing game or application.


I'm sure if a small group of Flash game developers teamed up "Humble Bundle style" they could release a bundle with multi-platform, DRM-free AIR games, with proceeds either going towards charities, or perhaps towards the open source developers working on the AIR binaries for Linux. In either case, the bundle would provide positive publicity for AIR.


I don't have the influence or resources to do this, but do you?



Friday, June 3, 2011

[Experiment] Drop Painter

This post can be found on the new blog at Experiment: Drop Painter
No, it's not painting with drops (though, that seems like a great idea for another project). Instead this experiment drops pieces of a painting down from above which eventually form to assemble a complete picture.

DEMO: http://iqandreas.isbetterthanyou.org/public/kirupa.com/square-contest-2011/


The code is written in AS3 and uses Box2D for the physics and MinimalComps for the components.

At first I wrote the code up as a prototype just to test a concept (and rather than rewrite the code cleanly, I just kept adding onto it so it became one tightly-coupled mess).

Later I entered it into a contest held on the Kirupa Forums, and modified it slightly to fit the contest theme.


The source is available on GitHub in case anyone is curious how it was achieved (and yes, I did cheat. It's not actually dynamic. The movement of all those shapes are "pre-baked" during the "Loading" screen and simply played back afterwards, which is why it is able to take up so little CPU on playback.

Tuesday, October 19, 2010

Understanding the AS3 Event System #3 - Easy Event Bubbling

This post can be found on the new blog at Understanding the AS3 Event System #3 - Easy Event Bubbling
This thread is part 3 in a "Understanding the AS3 Event System" series. It continues on the "office" illustration used in parts #1 and #2. If you have not read part 1, it is recommended that you do so:
http://iqandreas.blogspot.com/2010/10/understanding-as3-event-system-1-basics.html

This part describes how "Event Bubbling" works. Note that this is a strong simplification of the actual system (which is a bit more complex, but in the next part I will elaborate on that system), but for 99% of all Event uses, this is the only thing you really need to know about Event Bubbling.



At the office I work, a large part of our work system is set up as a hierarchy of responsibility and work delegation.

The Corporate Ladder
At the very top of the tree is Mr. Stan Stage. He's a great guy. Very friendly, a nice father figure, and a really good boss. He is the boss of all bosses, and in the end, everyone reports to him.

Since there is so much information passed around the office each day, he delegates a lot of the tasks to a handful of people who work right under him. These people are all "second in command". One of these second in command is my boss. Unlike Mr. Stage, my boss is very annoying and difficult, and to avoid his wrath, I will exclude his name, and instead just call him "My Boss".

My Boss has about 20 people working under him, including me. It's not a great position to be in, but it's still a very rewarding job. Some of us "third in command" workers have people working directly under us.

I am one of the lucky ones, and have five interns working directly for me. Since I am their boss, they obey my every whim, such as getting coffee for me each morning, or taking out my dry-cleaning. Even though they are only interns, they are still considered to be "fourth in command".


Since a great deal of what we do at the Office is reported via Events, my interns are expected to use the event system to report any changes just like the rest of us.

For efficiency's sake, my five interns have their desks very close to my cubicle, so whenever they dispatch an event (by standing up and shouting for example "I was hovered!") I hear it immediately.

Now, there are two types of Events. Events that Bubble, and Events that do not Bubble.


Non-Bubbling Events
Some Events are only important to the person which it actually happened to. For instance, one day one of my interns, Chris, stands up and yells "Hey everyone, I got a new car!"
dispatchEvent(new Event("new_car"));

A few of my other interns reacted. However, I honestly did not care. My Boss sure as hell doesn't care. And as nice of guy Steve Stage is, he really doesn't care either.

I'm not saying that Chris's Event wasn't important, in fact, it was quite important since it allows him to do his job better and will definitely affect his work. However, there is no need to tell as many people about it as possible. The only people who need to know about the event are people who specifically asked Chris to let them know whenever he got a new car.
chris.addEventListener("new_car", talkToChrisAboutTheCar);

Those Events do not Bubble up the corporate ladder.


Events that Bubble
Now, clicks are VERY important in my line of work (in fact, that's how we get paid).

We want to let as many people as possible who want to know about the clicks to know about the clicks, but if every single person just stood up and yelled "Someone was clicked!" whenever they found out about it, it would be one disorganized mess and you would hear about the same gossip from 8 different people. Instead, we have an organized system for letting everyone  in charge know about it.


Bubbling Events up the Ladder
One day Chris stands up and yells out to everyone "I was clicked!" (dispatching the event to everyone that may be listening to him. Not many people are usually listening to Chris (in fact, most people at the office don't even know any of my interns). So, Chris tells everyone listening to him about the click event.

Then Chris walks over to me and says "Andreas. I was clicked. All the information on the click is available in this file folder."

Now it's my turn. I stand up and yell "I was clicked!" (I could tell them "someone in my department was clicked", but since my interns work for me so closely, their work is considered to be part of my work) A few people are listening to me for the "clicked" event, (including Nico and Bob) and walk up to me asking for more information. I give them both the file so they have all the information on the event that they need.

Then, I barge into the office of my Boss, telling him all about the event, and handing him a copy of the information. He in turn switches on his fancy intercom system (since he is second in command, he gets certain perks, and is paid too much to have to yell across the hallway) and announces to everyone in the office "Attention anyone who is listening to me. I was just clicked." A few people are listening to him, and respond.

Finally, my Boss knocks on the door of Steve Stage and tells him all about the click event. Now, at last, Mr. Stage announces the click event for the last time, telling everyone who is listening to him about the click.

After that it is done. Everyone who needs to know about the event knows about it.


Now why is Bubbling so important?
Let's take the example of Betty, who works in accounting. In order to do her job property, she needs to know about every single time a client "clicked" an employee.

She could listen to every single employee for the "click" event, but this is a VERY inefficient system. And every time there is a new employee she would need to start listening to them, and when an employee leaves, she needs to remember to stop listening to them.

Instead, because of our nifty little bubbling system, Betty ONLY needs to listen Stage for the "click" event. Since those events bubble up to Steve, she will be notified of every single click event directly from Steve Stage.


EXTRA NOTE: Events only bubble upwards
Let's say one day I'm working at my desk, when a client clicks me directly instead of clicking one of my interns. I stand up and yell to everyone who is listening to me that "I was clicked", but I do not need to directly tell any of my interns about the click. Unless my interns are specifically listening to me, they will not know about the click and will keep carrying on their work undisturbed. The interns will NOT dispatch any "click" event either.

The only one who needs to know is My Boss. The events only bubble "up" the corporate ladder, not down.


So who was clicked first?
In order to file the proper paperwork (and hand out promotions or raises where needed) Betty needs to know exactly which person it was who was "clicked" first. Luckily, all this information is perfectly filled out in the Event object (the folder containing all the information).

There are two names in the Event object, "target" and "currentTarget". Flash assigns these two names automatically when the Event is dispatched.

These two properties tend to cause a lot of confusion among beginners. Sometimes they refer to the same person, sometimes they do not. To explain the difference, let's take another example.


Nico is listening to me for the "clicked" event.
andreas.addEventListener("clicked", onClick);

Chris, my intern, is clicked, and stands up and tells everyone about it. Nico doesn't even know Chris and therefore doesn't even know about the event. Chris tells me about the event and hands me all the information.

Now, I stand up and tell everyone "I was clicked". Nico is listening for the event, and walks over to me to gather all the information.

Then the event continues to bubble upwards to My Boss and finally Stan Stage.


target refers to the person who first dispatched the event. In this case, Chris would be the target.
currentTarget refers to the person you were listening to who told you about the event.

Think about "currentTarget" for a second. For Nico, currentTarget would refer to me, Andreas. However, since Betty is listening to Stan Stage for the Event, the currentTarget property in her event file would refer to Mr. Stage.


Using currentTarget to your advantage
Why does the "currentTarget" property even exist? I mean if you added the event listener to an object, of course you know what that object is, and therefore the property is pretty much worthless.

However, if used properly, it can save you a lot of code! For instance, perhaps you have several buttons on the stage "homeButton", "aboutButton", "contactButton", "newsButton", etc. You want the button to scale up when it is clicked. You could add the event listeners like this:

homeButton.addEventListener(MouseEvent.CLICK, homeButtonClicked);
aboutButton.addEventListener(MouseEvent.CLICK, aboutButtonClicked);
contactButton.addEventListener(MouseEvent.CLICK, contactButtonClicked);
newsButton.addEventListener(MouseEvent.CLICK, newsButtonClicked);

function homeButtonClicked(mev:MouseEvent):void
{
   homeButton.scaleX = 1.2;
   homeButton.scaleY = 1.2;
}
//etc...


That means, creating a different handler function for each button, which works, but creates a lot of extra code. Then if you want to change details of what happens when a button is clicked, you would need to update every single function.


Instead, you can create one single function which handles the clicks of all buttons. You can calculate which button needs to be pressed by using the "currentTarget" property.

homeButton.addEventListener(MouseEvent.CLICK, navigationButtonClicked);
aboutButton.addEventListener(MouseEvent.CLICK, navigationButtonClicked);
contactButton.addEventListener(MouseEvent.CLICK, navigationButtonClicked);
newsButton.addEventListener(MouseEvent.CLICK, navigationButtonClicked);

function navigationButtonClicked(mev:MouseEvent):void
{
   var pressedButton:DisplayObject = mev.currentTarget as DisplayObject;
   pressedButton.scaleX = 1.2;
   pressedButton.scaleY = 1.2;
}


Which uses only a single function! Now, if you need to change the scaling to 1.3, you only have to update it in one single place!


If you want to attach additional properties to the buttons, (such as setting some custom scale value for each button) you can use the Dictionary object. Look in the FAQ under the appropriate category for links to explanations and example code:
http://iqandreas.blogspot.com/2009/09/most-common-flash-questions-as3-faq.html



This is how Flash bubbles it's events. Next step, how to make your own events bubble.

Tuesday, October 12, 2010

Understanding the AS3 Event System #2 - Custom Events

This post can be found on the new blog at Understanding the AS3 Event System #2 - Custom Events
This thread is part 2 in a "Understanding the AS3 Event System" series. It continues on the "office" illustration used in part 1. If you have not read part 1, it is recommended that you do so:
http://iqandreas.blogspot.com/2010/10/understanding-as3-event-system-1-basics.html


I originally wrote this thread as a response to a Kirupa forum thread:
http://www.kirupa.com/forum/showthread.php?t=355040


This is my first draft, so any opinions or thoughts are deeply appreciated, especially if there is anything you still don't fully understand or would like me to clarify further.



Listen, don't tell my boss, but those days when work gets slow, I fire up some StarCraft! StarCraft is no fun alone, so Nico, Bob, Larry, and I all play against eachother. The problem is that we all need to be logged on at the same time in order to play together. I'm the one who plays the most, so I am the "Game Master" - the one who starts up the server, chooses a map, and waits for everyone else to join in.

We need some way to alert eachother when I start up a StarCraft game, AND keep it a secret from my boss (he reads all our emails, so I can't tell them via email). So, we use the Event system!


Custom Event Strings
We have planned that whenever I am about to start up a new game, I stand up and yell out to everyone "I am about to call Yamato!" (who our boss assumes is one of my Japanese clients)

Everyone knows that the custom event string (or event type) for when everyone listening should play starcraft is "Yamato". So, ahead of time, Nico, Bob, and Larry listen for my "Yamato" event:

Code:
homeButton.addEventListener("Yamato", startPlayingStarScraft);
Now, we may start playing dozens of different games, and I have chosen a different "code name" as the event string for each type of game:
Code:
homeButton.addEventListener("MarcoPolo", startPlayingAOE);
homeButton.addEventListener("Gelinor", startPlayingRuneScape);
homeButton.addEventListener("Germany", startPlayingCOD);
homeButton.addEventListener("Orcish", startPlayingWOW);

Custom Events
Now, I could create a different type of Event Folder for each type of game, such as StarCraftEvent, RuneScapeEvent, AOEEvent etc.

Each type of event file would have information inside of it, for instance, the "StarCraftEvent Folder" may have the following properties:
> the target - Me, since I'm the one "dispatching" the event
> the type - the custom event string, in this case "Yamato"
> map - the StarCraft map we will be playing in
> players - a list of all players
> settings - the game settings

And our class would look something like this (note that "target" and "type" are automatically inherited by the Event since you "extend" it)
Code:
public class StarCraftEvent extends Event
{
    public function StarCraftEvent(the_type:String, the_map:SCMap, the_players:Array, the_settings:GameSettings)
    {
        //Since you extend the Event, let the super class know a few more additional details
        super(the_type);
        
        map = the_map;
        players = the_players;
        settings = the_settings;
    }
    
    public var map:SCMap;
    public var players:Array;
    public var settings:GameSettings
}
This would be my totally custom made event class! Perfectly customized for whenever we want to start a StarCraft game, allowing everyone to get the information they need!


Dispatching the Custom Event
This is exactly as simple as it was dispatching the "clicked" event:
Code:
//Create the event
var players:Array = [Andreas, Nico, Bob, Larry];
var scEvent:StarCraftEvent = new StarCraftEvent("Yamato", lostTemple, players, defaultSettings);

//Dispatch the event (and it's folder containing all the info)
dispatchEvent(scEvent);
That dispatches an event which alerts everyone who is listening that I am about to start up a StarCraft game.

So, Nico, Bob, and Larry run up to my cubicle and I hand them all the StarCraftEvent Folder containing ALL the information they need to join in the game.


Do you really need to create Custom Events?
Now I can create a new Custom Event for each and every game we play and that would alright.

But I noticed, no one really reads the information in the Event Folder! I spent good money putting together and printing out all the information for those folders, and no one reads them! They get the file from me, then they run back to their own cubicles, fire up the game, and throw the Event Folder directly into the trash.

When you think about it, do they really NEED all that extra information such as maps or players? They will find all that information out anyway when they start up StarCraft. There really is no use going into all the hassle of creating custom events!

Instead, what if I print out a plain old Event Folder? All it says is the "target" and the "type", but if they want more information (which one one does) they can ask me for it directly.

FORGET about the hassle with the StarCraftEvent class, and just do this:
Code:
var eventFolder:Event = new Event("Yamato");
dispatchEvent(eventFolder);
99% of the time. That is all you will ever need. You save a lot of unnecessary work.


You don't always need to create custom Events, usually it is enough just using custom Event Strings.


That is Custom Events 101


Monday, October 11, 2010

Understanding the AS3 Event System #1 - The Basics

This post can be found on the new blog at Understanding the AS3 Event System #1 - the Basics
I originally wrote this thread as a response to a Kirupa forum thread:
http://www.kirupa.com/forum/showthread.php?t=355040

This is my first draft, so any opinions or thoughts are deeply appreciated, especially if there is anything you still don't fully understand or would like me to clarify further.


Imagine your code as one big office room. That office has about 100 or so cubicles, with each cubicle representing a different object. For instance, if you have 5 Buttons on the stage, it's not one "Button" cubicle, but instead 5 different cubicles, one for each button instance.


The Event String/Event Type
Now, I'm sitting in the "homeButton" cubicle. One day, I get an email from my boss who tells me I have been "clicked". So immediately I stand up, and yell out into the hallway so loudly that everyone can hear "I HAVE BEEN CLICKED!"

Now, the boss may have A LOT more information, such as where I was clicked, how many times, if any of my children were clicked, and a lot more information. However, I won't stand up and yell out to everyone in the building all that information. That is quite wasteful, and if I got several of those emails a day, I would soon get tired of spouting out all that information.

Instead, to save energy, I only tell everyone "I have been clicked". That is me telling everybody the event type, also known as the event string.


Listening for Events
Back up a few hours (before the event string). I have a friend named Nico sitting in the art department (his cubicle is labeled "currentImage" though that's not really that relevant). His boss told him "Whenever Andreas in the homeButton cubicle is clicked I want you to draw an image of a house and send it right to me."

Now, Nico could get up out of his seat every five minutes, walk over to me, and ask "Hey, Andreas. Were you clicked yet?" I say no, so he walks back to his cubicle and sits down. This would happen again and again, and neither of us would get any work done. This is VERY inefficient. Nico could reduce this and only check with me once per hour, but he wants to know immediately when I am clicked. So that is NOT an option either.

Instead, Nico sits in his cubicle continuing his regular work, and in the meantime, listens out in the hallway for my voice. Now, at around noon I yell out "I was keypressed!" He hears my voice, but he really doesn't care about the keypresses. So, he ignores what I say, and continues working. Then another guy in the cubicle (Larry, a really annoying guy) yells out "I was clicked!" Since Larry is not as good looking as Andreas, and The Boss didn't tell Nico to listen to Larry, Nico ignores him completely.

Because, Nico is only listening to Andreas (in the homeButton cubicle) for the "clicked" event. When he hears the event, he needs to start drawing the house (which looks something like this in AS3):

Code:
homeButton.addEventListener("clicked", drawHouse);
The Event is dispatched
Now, fast forward back to where we were. Me (Andreas) gets the call from my boss telling me I was clicked. So I stand up and yell out to everyone. "I was clicked!"

Two people were listening for my "clicked", Nico and Bob (the guy from 'contentManagement', a very talkative fellow) Nico rushes up to me excited "Hey Andreas. I heard about the click. That is awesome! Congratulations! But tell me more about the event! Why were you clicked? Where were you clicked? Who clicked you? Why did they click you?"

I could spend the next 5 minutes explaining all the juicy details to Nico, but then I would have to repeat all this information to Bob (which is very inefficient, and Bob is a busy man and doesn't want to wait). So instead, I print out all the information on the "clicked event" and put it into a Folder which I give to Nico. I give the folder to both Nico and Bob so they can use the information in it and look at it as they please. This folder is the Event object (more details on that later)

Immediatly Nico rushes to his art studio in his cubicle and gets to work at "drawHouse()", however, now he has the Folder (the Event) he can use that information while drawing the house, and therefore passes it into the function as a parameter:
Code:
function drawHouse(event:Event)
{ /*Draw stuff in here...*/ }
The Event
To make sure that everyone gets the information they need, there are VERY strict protocols to what the Event Folder needs to contain.

The following pages with information are required for standard Event Folders
>the target - the person dispatching the event, which in this case is me, Andreas (or actually the homeButton cubicle).
>event type - the type of event (aka event string), in this case "clicked".
(there are a few more pages in the file, but that's mostly the small legal mumbo-jumbo fine print that no one reads anyway. You will be fine ignoring them for now.)

This is a standard Event file. But hold on, there was A LOT more information which is missing here! If I hand Nico a file with only those two pages of information in it, he will still wonder "Where were you clicked?" among MANY other important questions. Luckily, the company already has a neat system figured out!


The MouseEvent
Now, the company I work for has a second type of file, a "MouseEvent File". This file extends the standard Event File. That means that the MouseEvent file has all the information contained in the plus a lot more information, perfect for when a "clicked" event happened.

It has the standard two fields (target and type) PLUS these additional pages with information:
>localX
>localY
>stageX
>stageY
>altKey
>ctrlKey
And a whole lot more!

Note that this MouseEvent file ONLY is allowed to be used when dealing with events that had to do with the mouse, such as "clicked", "hovered" etc. The file should NOT be used for events that had to do with the keyboard, "keypressed" or "keyreleased". Those events should instead use a specialized KeyboardEvent File with it's own special properties.


So I print out all the relevant information and hand both Nico and Bob a "MouseEvent" folder. Using that information, they draw the houses, or display text, or whatever they want to do with the information.

(Extra note: Maybe Bob didn't even need to see the file. Maybe he just needed to know that I was clicked, so when I hand him the file, he may not even open it or look at the details of the click using the information inside. That's fine by me, but I still need to create the file in case there is someone out there who actually needs the information.)


Creating the MouseEvent
Bob and Nico don't want to wait for me to print out and collect all the papers needed in the MouseEvent file. They want the information to be ready the second they step up to my cubicle. So, BEFORE I stand up and tell everyone I was clicked, I create the folder ahead of time for quick and easy access. THEN, I dispatch it to all who are listening.

This is how it looks in ActionScript:
Code:
//create the folder with all the information in it
var eventFolder:MouseEvent = new MouseEvent("clicked", bla, bla, localX, localY, bla, bla, bla, bla, more bla);

//Now stand up and tell everyone I was clicked
//The "eventFolder" already says the event type is "clicked",
// so I don't need to repeat myself when dispatching it.
//All I need to do is dispatch the folder and Flash will do all the dirty work
dispatchEvent(eventFolder);
Now Nico and Bob (and whoever else is listening) can react to it and get to see the folder I sent when dispatching:
Code:
function drawHouse( andreasEventFolder:MouseEvent )
{ /*Draw stuff in here...*/ }
That is Events 101.


Thursday, June 3, 2010

What is the point of this Blog?

I recently had to write a summary of the blog, and thought it might be a good opportunity to repost this information here and make it clear to all my thoughts and purposes of this Blog.

This blog is a collection of information focused mainly on ActionScript and Flash, with emphasis on game development, plus a little bit extra thrown in. It is aimed to be readable by beginners and not only experienced developers.

Articles are typically in one of the following categories:


The posts also strive to be unique. "If you can find it from 100 different sources on Google, there is no use in reposting what is already out there." Though, I may link to good articles, but I try to avoid writing repetitious information, clogging up the already very filled internet.


If there is any part of ActionScript you want more information on, or have an idea for a good blog post, leave a comment in the section below. A blog isn't much use if the information is irrelevant to it's readers.

Cheers,
Andreas J. Renberg
http://iqandreas.blogspot.com/


And now on to SWF Protection! :)

Tuesday, May 11, 2010

A Game a Week #1 - Temperature

Sammo over on the Kirupa Forums has started a new "game" (I'm really not sure what to call it) on creating games.

I'll just quote him...
Welcome to the first A Game a Week, this is an experiment inspired by 2D Boy's Experimental Gameplay Project. The idea is simple, you have one week to make a Flash game, from concept to production. You are not required to enter, it is not a contest, it is just for fun and for practice. Most importantly though; it is not a contest.

The rules are very few and very simple. The rules are:
  • You must include the FLA (or AS or even FXG if you're feeling fly) file.

  • That is all.

    This week's theme is Temperature, and the deadline is May 18, 2010.


    For more details, visit the official Kirupa thread:
    http://www.kirupa.com/forum/showthread.php?p=2553233#post2553233


    If I have enough time among all my work, I will try to get a submission in, but I tend to procrastinate, so any work will likely be done on the 17th. ;)

    Sunday, April 25, 2010

    Getting started with Flash Player 10.1

    Flash Player 10.1 added several neat multi-touch, gesture, and accelerometer input features. There are several more neat features of the new Flash Player, but the new input controls are what I find the most captivating (that, and global error handling, FINALLY!). The rest can be found on Adobe's website:
    AdobeLabs - Flash Player 10.1 Features and Enhancements

    Adobe really put a lot of effort into getting the newest version of Flash Player to work on numerous devices, naming this project the "OpenScreen Project". Quoting Adobe - "With support for a broad range of mobile devices, including smartphones, netbooks, smartbooks and other Internet-connected devices, Flash Player 10.1 allows your content to reach your customers wherever they are." [side note - sadly, iPhone support was shot down]


    Flash Player 10.1 is still in the "prerelease stage", meaning it is not released as an "official" or currently updated version just yet. I'm not sure if bugs are being ironed out, or if Adobe mainly wants to wait until Flash CS5 is out. However, the new player is still available for developers who want to test out the new features.

    So far, FP 10.1 seems to be working just fine for my every day uses, and haven't run into any major bugs yet. In fact, (since I'm in Linux still) the old Linux Flash Player (version 10.0.45.2) had several bugs which were never ironed out, and according to several Google results were quite common. However, with the new version, those bugs seem to be gone (at least so far):
    [Solution] Flash sound stops working in FireFox on Linux Ubuntu 9.10
    [Solution] Adobe TV crashes FireFox on Linux Ubuntu 9.10


    Since 99.8% of your site/application/game users won't have version 10.1 installed, I really don't recommend using it for your sites just yet. However, if you have a phone or computer with multi-touch capabilities it might be fun messing around with the new features. In addition, if you read up on the classes and functions enough now, by the time it is fully released, you can be first in line when clients are looking for the newest features for their product.


    So, where do I get started?

    FIRST, you need to download the actual Flash Player 10.1. As with Flash 10, the browser and standalone versions are two different things, so if you update the browser player to 10.1, the standalone player will still be the old version and vice versa, so unless you plan on keeping the old player for any specific reasons, remember to update them both.

    There is also a difference between the debug version and the regular version. Basically, the debug version is good if you do a lot of testing, since the error messages show up as dialogs, along with several other features not available in the "regular" release of the Flash Player. Otherwise, errors are silently ignored, which is good for regular users, but really annoying if you can't get your code working right, and you are having a hard time figuring out what's going wrong and where.

    All versions of the player can be downloaded here:
    http://labs.adobe.com/downloads/flashplayer10.html


    THEN, all you need to do is download the new SWC library with all the new classes. I'm pretty sure they are just the "shells" for the classes which expose all functions and properties rather than contain actual code, just as the ActionScript files for MovieClips don't contain the actual code for them, but just expose functions to allow code hinting etc for developers. [a VERY good read on the matter]

    I was worried I would need an updated compiler, but to my joyous surprise, you can still keep using Flash Professional, Flex Builder, the Flex SDK, or whatever compiler you use without any modifications. There should be dozens of tutorials on importing SWC libraries into your current editor, but if you can't find anything relevant, ask in the comments section, and I will lead you in the right direction. Don't forget to post what type of IDE you are using (Such as Flash Professional CS4 or FlashDevelop etc).

    The SWC can be downloaded on the same page as the Flash Player (how convenient)
    http://labs.adobe.com/downloads/flashplayer10.html#pgswc


    Downloaded and ready! Teach me how to use it!

    Sadly, I don't have any tutorials for it (I don't have a touchscreen or even a mobile device newer than 10 years old) but several others out there have already put up tutorials for FP 10.1 development.

    gotoAndLearn - Multi Touch Gesture Applications
    Multi Touch in AS3 / Flash Player 10.1 - Part 1. Setting Up
    Multi Touch in AS3 / Flash Player 10.1 - Part 2. TouchEvent & MouseEvent Sequences


    I'm in need of a lot more tutorials and examples, so if you know of any other good sources, or have written any good tutorials yourself, just leave a link in the comments section! :)


    Some further reading

    As always, I am never the first to write about things, so here are some helpful links which hopefully helps someone out there.

    Adobe Labs - Adobe Flash Player 10.1
    Introducing Adobe Flash Player 10.1 public prerelease
    Flash Player 10.1 prerelease software demos and interviews
    Adobe TV - Multi-touch capabilities of Flash Player 10.1
    Kirupa Forums - Disappointing FP 10.1 First Impressions
    TourDeFlex - according to Adobe, some examples should include some FP 10.1 features as well. Still very neat if you haven't used it before!


    Good resources for FP 10.1 development

    Keep these links in your toolbox. They usually come to use quite a bit:
    ActionScript 3.0 Language Reference (with updates for Flash Player 10.1)
    ActionScript 3.0 Developer's Guide (also with FP 10.1 updates)
    Adobe Forums - Flash Player 10.1
    Adobe Bug tracking and management - On case you do find anything wrong with the new version. When submitting, remember to check for existing bugs, as chances are you aren't the first person ever in the world to run across that bug. ;)



    If anyone has any demos of what they have accomplished with the new features in FP 10.1, leave a comment and share your work with others (source code is appreciated, but not required). I will provide the SWF hosting if you require it.

    Wednesday, March 10, 2010

    ActionScript Blogs to Follow [Open Post]

    A Google search for "ActionScript blog" returns over 5,790,000 results. In a widespread internet world like this, it can be difficult (especially for beginners) sifting through which information is reliable and helpful, and which simply isn't (hopefully this blog is not in the latter category)

    Here is my personal list of blogs I find quite worthwhile to bookmark and check up on from time to time.

    Thursday, February 11, 2010

    Optimize AS3 for speed - Bitmap filters reply

    I originally posted this as a reply to a comment on MichaelJamesWilliam's blog entry "Learn how to Optimize your AS3 Code". The spam catcher kept refusing to submit it (I'm guessing because of all the links), so I reposted the reply here.



    kustrle February 11, 2010 at 7:51 am
    I was sure pixel perfect collision detection already first check if two objects are overlaping. Is there any way of reducing lag that comes from glow, blue, etc without photoshop? Since we lose flexibility there too. If we want to change glow to other color later it will be much harder. Can we tell flash to convert those objects to some kind of bitmap picture and then forgot about all filters? Great tutorial!


    @kustrle - Yes, it is possible to save the "filtered" version of DisplayObjects as BitmapData and use that the entire time.

    Tuesday, February 9, 2010

    The Language Reference at the tip of your fingers!

    There is no question or dispute about it,
    If you want to be a good ActionScript developer, you need to learn how to use the ActionScript 3.0 Language Reference. (Unless you have decided to do all your coding using only primitives...)
    I'll write a guide on how to use the language reference some time in the future, but until then, it still needs to be convenient and easy to get to. I will show you how to save the language reference to your hard drive (faster than loading it in from the internet, and then it's also available when you are offline!), and then add it to your bookmarks toolbar.

    The end result will look something like this:



    I will be using FireFox (version 3.5.7) running on Windows XP. It should be fairly straightforward, and pretty much the same for any browser or operating system, but if you have any difficulties, leave a comment. If you have gotten this to work in a different operating system or browser, please share your results.


    Step 1 - Find and download the ActionScript reference from Adobe's website

    The newest version of the language reference can be found at:
    http://help.adobe.com/en_US/AS3LCR/Flash_10.0/index.html

    Note that Adobe often throws around and rearranges their site, so if that should happen, this site will always link you to the most up to date version of the language reference:
    http://tinyurl.com/ykacx95


    About at the bottom of the page of the online reference, it should say something like "Download a standalone ZIP file version of this reference, including its own local search for offline use, here:" with a link to the ZIP. The current link is as follows:
    http://help.adobe.com/support/documentation/en/flash/10/ActionScript3LangRef.zip

    Save that ZIP file (about 6MB) to your desktop, and proceed to step 2...



    If you are using Flash CS3, the online version of the language reference can be found here:
    http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/

    I can't seem to find a downloadable ZIP, however, if you installed CS3 correctly, the language reference should already be stored on your computer in the following directory:
    C:\Documents and Settings\All Users\Application Data\Adobe\Flash CS3\en\Configuration\HelpPanel\Help\ActionScriptLangRefV3\index.html


    If you are using any other version of ActionScript (such as AS2, Flex, FlashLite etc), the entire list of avialable language references can be found at:
    http://www.adobe.com/devnet/actionscript/references/
    However, it seems that only the Flex Language Reference and the Flash CS4 Language Reference can be downloaded as ZIP files. Sorry. :(



    Step 2 - Extract the ZIP file to an appropriate location

    If you can't do this one on your own, you have more to worry about than learning ActionScript.

    You can extract the directory to any place that is convenient for you, however, if you decide to move it later you will need to redo the entire procedure, so choose wisely!

    Some recommended directories:
    c:\Documents and Settings\All users\Documents\AS3 Language Reference\
    c:\Documents and Settings\All users\Application Data\Adobe\AS3 Language Reference\
    c:\Program Files\Adobe\Flash CS4\AS3 Language Reference\
    c:\Program Files\Adobe\AS3 Language Reference\
    c:\Program Files\Mozilla Firefox\AS3 Language Reference\
    c:\Programming\Flash\Language References\AS3 Language Reference\
    c:\AS3 Language Reference\

    I will be using the first option for this tutorial as it will be the least likely to be overwritten in case any programs update.


    If you are using CS3, play it safe and keep the language reference in the directory where you found it. If you want to have it elsewhere, make a copy.



    Step 3 - Add "index.html" and "all index pages"


    EDIT: For some reason the context menu option "Open selected links in new tabs" seems to have disappeared, so in order to continue the tutorial you need to install one of the following add-ons:
    Linky - https://addons.mozilla.org/en-US/firefox/addon/425
    Multi Links - https://addons.mozilla.org/en-US/firefox/addon/13494
    Snaplinks - http://snaplinks.mozdev.org/installation.html

    For this example, I will be using "Linky", but you are free to use whatever plugin you prefer.


    In the directory you downloaded the language reference to, open the "index.html" file into FireFox (or whatever browser you are using).

    The site's url should say something like
    file:///C:/Documents%20and%20Settings/All%20Users/Documents/AS3%20Language%20Reference/index.html

    And you should see a page like this

    The main index page for the ActionScript 3.0 Language Reference

    To begin, bookmark "index.html" and rename it to "Main Page" or something and place it in a new bookmark folder named "AS3 Language Reference".

    For convenience, I added the bookmark folder directly to the "Bookmarks Toolbar", but you can keep them hidden away in the plain old bookmarks menu if you prefer.


    Next we will be adding a "search feature" (more like an index with CTRL+F) Remove the "index.html" text from the url bar and hit enter. This should bring up the folder contents in FireFox with the following url:
    file:///C:/Documents%20and%20Settings/All%20Users/Documents/AS3%20Language%20Reference/


    Select all the links you see from "all-index-A.html" to "all-index-Z.html", right click the selection, and (at least in Linky) choose "Open selected links in tabs". After a while, you should have 27 new tabs opened. You can close down the "folder view" so it doesn't get included when bookmarking.


    Go to "Bookmarks > Bookmark all Tabs..." or hit "CTRL+SHIFT+D". Choose where to store these bookmarks, and name the folder for them something like "Search". It may take a few seconds, but once the bookmarks are saved, you can close down those pages. This is easiest by just closing and reopening the window, but if you have TabMix Plus plugin installed, there is a very handy "Close other tabs" option.

    Linky - open selected links in tabs

    Save all tabs as bookmarks

    A quick alphabetical index of classes, properties, and functions is now available in your bookmarks


    For the next steps, you will be repeating this procedure quite a bit.

    Also, if it makes it easier, you can add the root folder where the language reference is stored as a bookmark as well (I named mine "Browse Folder")



    Step 3 - Add the packages


    Next we will be adding the following packages as sub folders of the bookmarks menu:
    adobe.* (only a few files)
    air.* (if you don't develop in AIR at all, you can ignore this one)
    fl.* (Flash components)
    flash.* (All the actual class files - this one is the most important!)

    This part is the one that takes the longest. Unless you have a trusty army of Oompah Loompahs to do the job for you, prepare to take out at least half an hour in bookmarking them all. If you have a short attention span, bookmark them small parts at a time over time.

    In any order you like, start by opening one of the subfolders with the matching package name, and in most folders, you will need to open an additional sub-folder package.

    I'm going to start with "flash.accessibility" (in folder "flash\accessibility\") and start working down the list in alphabetical order until the entire flash directory is added.

    Use Linky to open the list of classes into your tabs


    Keep doing this to all 4 folders (and their respective subfolders) until you get an organization something like this in your bookmarks toolbar:

    Browsing for the documentation for flash.display.MovieClip


    Wohoo!! Almost done... (After all that you probably don't want to see another bookmark again, but bear with me. It is definitely worth it and VERY convenient once it's done!)



    Step 4 - The global package and Appendix



    There are several classes just laying their in the main folder that don't have a package. You could add them directly to your bookmarks toolbar, or you can group them into a new "global" folder to avoid clutter.

    Better organized global classes and functions bookmarks

    I found, the easiest way to track down all global classes, instead of guessing which ones are classes and which ones are just HTML pages, open the page named "class-list.html". It will contain a list of all the global functions and classes.

    Note that even though the classes are organized into separate HTML files, the global functions are all stored in one single HTML file (named "package.html"). So, instead of selecting all links on the page, only select the classes, and bookmark them. After that, go back and bookmark "package.html". If you have any use for it, you can also bookmark "package-classes.html", which is basically a list of all classes and functions in the top level package.

    You can even add the pages "operators.html", "statements.html", and "specialTypes.html".


    Finally, the Appendix ("appendix.html") contains pages such as a list of errors and what they mean, some AS2 to AS3 migration help, and other information. You can either add this single page and bookmark it, or select all outgoing links and bookmark those instead, creating a subfolder named "Appendixes".


    The only page left is "conventions.html", and unless you will be checking on it every few days, I wouldn't bother adding it as most of the Language Reference conventions are quite self-explanatory anyway.



    Last thoughts



    So, that's it. If you did everything right you should have a bookmarks menu which is easy to navigate around in, and has really helped me at times.



    An added bonus is that if you start typing in something in the address bar, FireFox will automatically recommend pages in your bookmarks.
    Firefox will auto-complete any text you type in with a class in the language reference from the bookmarks if a match is found


    I'll create a post in the near future which better uses the "search" ability of the language reference, but that is yet to come.

    Saturday, December 5, 2009

    Simple AS3 VolumeKnob component

    An entire month went and not a single post... Sadly, there is a lot of valuable information I learn that I don't put on my blog, which I should, I just never get around to it.


    I still haven't written any documentation for it, but I thought I'd throw this out there in case there is anyone else trying to create the same effect.

    Pass in a DisplayObject as the "knob", and when the user holds down the mouse and drags around, the volume will increase when rotated to the right, and decrease when rotated to the left.

    It is "continuous", like those digital volume knobs, where you can turn without limit left and right, and even if volume is all the way down to 0, you can still keep turning left etc.

    Files stored here:
    http://iqandreas.isbetterthanyou.org...VolumeKnob.zip
    The ZIP contains the class (src/VolumeKnob.as) and one simple example file (src/Main.as) as well as a compiled SWF in the bin directory.
    (Thanks to a very helpful donor for the webspace!)


    Better description, ASDoc, and examples to come. Refer to comments inside of AS file for more details until then.

    Feel free to use and distribute the class freely, but NEVER pass it on as your own work telling others you made it. PLEASE tell me if you end up using it for any projects. It's not a requirement, but it I would like it.

    Thursday, September 17, 2009

    Most common Flash Questions (AS3 FAQ)

    When you help out beginners as much as possible each day, you tend to hear the same questions again and again (and again, and again).

    Ignoring the fact that when I was little, I used to think FAQ was a bad word (not joking), I have here compiled a few links for threads with the most frequently asked questions in the Kirupa.com ActionScript 3.0 Forums.


    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    Hands down, with no doubt possible in anyone's mind the absolute #1 error. There are 2 possible causes:


    Duplicating a MovieClip (or at least creating a new version of whatever you pass in)
    http://www.kirupa.com/forum/showpost...80&postcount=3
    http://www.kirupa.com/forum/showthread.php?t=333120
    http://www.kirupa.com/forum/showthread.php?t=334933 - Didn't realize the "constructor" property was so vulnerable. Nice discussion.


    The difference between instance name and library name
    http://www.kirupa.com/forum/showthread.php?t=333041


    The Dictionary Class (Passing in custom variables to Events)
    Personally, I really like using it since it allows you to pass in other variables to events such as telling which URLs go to which buttons, so you can use one function for the onClick event.
    http://www.kirupa.com/forum/showthread.php?p=2484903
    http://www.kirupa.com/forum/showthread.php?t=331118
    http://www.kirupa.com/forum/showthread.php?p=2501990 - Some sample usage


    Wow! How can I learn to be a great coder like you?
    First of all, I'm good with Logic, but sadly I often use Flash instead, which is often similar, just uglier and meaner.
    http://www.kirupa.com/forum/showpost...51&postcount=6 - Some great reading
    http://www.kirupa.com/forum/showpost...85&postcount=2 - The Flash and PHP Bible


    The advantage of using static properties and functions
    I need to dig out an old MSN messenger discussion on this as well. It's on my rediculously long todo list.
    http://www.kirupa.com/forum/showthread.php?t=334492


    The strange way frames work in Flash
    http://www.kirupa.com/forum/showthread.php?t=325891 - How frames really work. Might need some updating as this was posted early on when I was first learning Flash.
    http://www.kirupa.com/forum/showthread.php?t=325884 - This guy still owes me a beer


    There are plenty more, I just want to avoid digging through all 600+ of my forum posts for the gold nuggets. If anyone finds any more (by me, or anyone else for that matter) comment.

    Wednesday, September 9, 2009

    Error: Error #2071: The Stage class does not implement this property or method.

    Error: Error #2071: The Stage class does not implement this property or method.
    at Error$/throwError()
    at flash.display::Stage/set x()
    at Untitled_fla::MainTimeline/frame1()[Untitled_fla.MainTimeline::frame1:1]
    Similar to Error #2069, Error #2071 occurs when you try to set stage properties that have been overriden.

    To quote the ActionScript 3.0 Language Reference:
    Quote:
    In addition, the following inherited properties are inapplicable to Stage objects. If you try to set them, an IllegalOperationError is thrown. These properties may always be read, but since they cannot be set, they will always contain default values.
    • accessibilityProperties
    • alpha
    • blendMode
    • cacheAsBitmap
    • contextMenu
    • filters
    • focusRect
    • loaderInfo
    • mask
    • mouseEnabled
    • name
    • opaqueBackground
    • rotation
    • scale9Grid
    • scaleX
    • scaleY
    • scrollRect
    • tabEnabled
    • tabIndex
    • transform
    • visible
    • x
    • y
    Logically thinking, you can't really set the x, y, or rotation values of the stage, since it is supposedly "God", what everything else in Flash is measured against. Sure, if the user is running a SWF as a projector or through the debugger, they can move the dialog box around, however, this doesn't really change the x and y values of the stage, as the stage will still always be at 0,0 inside of its container.

    If you want to measure any farther, you will have to start measuring in the operating system's coordinate space. That's going a little too far, and is even outside of Flash's capabilities.

    Also note that the following stage properties are overriden, and throw errors if you try to set them. These are different than the properties listed above because they will hold actual values, not just the default ones, but you are still not allowed to modify them.
    • height - can be read, but throws an IllegalOperationError if set
    • width - can be read, but throws an IllegalOperationError if set
    • stageHeight - is able to be set, and will not throw an error, but it seems as though changing this property has no effect on the stage, at least not when run in the Debugger Player
    • stageWidth - is able to be set, and will not throw an error, but it seems as though changing this property has no effect on the stage, at least not when run in the Debugger Player
    • textSnapshot - cannot be read or accessed. Should be in the list above, but I'm not sure why Adobe didn't include this property to the list.

    NOTE: Unless you like boring nitty gritty details, you can just stop reading right here. The rest is just for reference.

    In addition, some properties and methods cannot be run outside of the stage's security sandbox without the proper permissions, so those methods are overridden just so Flash can check their security credentials. They act just as the regular methods they override with the difference that they will dispatch a SecurityError if accessed by an object outside of the current sandbox.

    The affected properties all have to do with children and are "mouseChildren", "numChildren", and "tabChildren". The affected methods that have to do with containing children are addChild(), addChildAt(), removeChild(), removeChildAt(), setChildIndex(), and swapChildrenAt(). Finally, the only other affected methods have to do with Event Dispatching, and are all overriden for security checks; addEventListener(), dispatchEvent(), hasEventListener(), and willTrigger(). Strangely enough, removeEventListener(), doesn't require a security check...

    However, don't bother memorizing them as these methods will act just like any other display object to outside users, and won't affect your code at all.



    Thanks to Senocular for pointing much of this out.