Quick post here. I’d like to share this very quick way to create an automatic ID or index to your class instances. Mostly I pass an index as parameter to the class instance, or I use a public var to set the index. Using this way it is very easy to create an automatically filled index, since you have to set this up once and never worry again
As you see, I have created a static variable global_index, which is always the same to all MyObject classes. I also created a public constant ‘INDEX’, which would be unique in every instance. When the MyObject instance is created the index will be set to the global_index, and the global_index will increase by one. So that’s basically the trick to create the auto-increment index for your AS3 class.
Quick post here, a simple solution I found to have multiple keys enabled. Maybe most real game developers know better or more elegant solutions, but I found this useful enough to share it with you.
Here we go. Add these variable to your class. This is a Dictionary, which allows you to associate a value with an object key.
privatevar currentKeys:Dictionary = new Dictionary();
Then, in your constructor or wherever you assign eventListeners, add these (well-known) listeners, with the callback functions:
I found that if you use some 3 or 4+ combinations of keys at the same time, the keyboard events are not triggered anymore, which is a bit of annoying bug in the FlashPlayer. I mean pressing forward and left and shooting at the same time could be a problem? Well; Hope this helps, I think its very easy and a great usage of the Dictionary.
Who follows me on twitter already noticed I’ve created a little app inspired by scribbler from zefrank. I also found another cool version of Mario Klingemann aka Quasimondo called scribblerToo. But the one where it all started is the javascript version of Mr.Doob. I wanted to try this in flash, and called it findClosest. It’s not as great as the other versions, but I really think there are some interesting things in here.
The trick in this little application is to store each mouse position, locate the mouse position and find the closest points around it (from the stored data) and draw some lines between those points. Well that code isn’t very exiting, because most people know how to find the distance between 2 points, and basically there are 2 ways find this:
// option 1: Using the build-in function var distance:Number = Point.distance( point1, point2 );
// option 2: Using Math var distance:Number = Math.sqrt( point1.x * point2.x + point1.y * point2.y);
The results are amazing and I love the fact that even if you can’t draw, it looks really cool
Store lines as small as you can
I was already trying to find a way to store lines in a format I can reuse for my artworks. Most artworks are random but I am looking for a way to have more control. The first step would be the ability to control the (what I call) movements. So in this little experiment I’ve tried to find a way to store the lines into a compact file, which can be redrawed by the app. I’m really exited about this. So I’ve started to save as a plain-text file writing something like this:
It’s readable code, and easy to These are 56 chars for 4 points. So I tried to make it more smaller using this:
{100,300},{110,340},{125,350},{125,350}
I’ve removed the x and y from the file, because I know that it’s always a pair of x and y values. Alright.. now I have 40 chars which represents 4 points, so that saves me 16 chars. Can this be done more smaller?
100,300,110,340,125,350,125,350
Yes, sometimes basic is the best. I removed the brackets. I know the odds are the x values, and the evens are the y values. It’s always x,y,x,y,x,y,x,y etc. So now I have 32 chars to store 4 points.
The application doesn’t know where I start pressing and releasing the mousebuttons. I have to know this, otherwise all my lines are just 1 big line instead of multiple lines. When pressing the mouse, I want to start with an graphics.moveTo function.
So what I did is this:
100,300,110,340,125,350,125,350&m=0,2
&m=0,2 means I have released the mouse on point 0 and point 2. A point referrers to the x and y position.
I think this is almost the smallest I can get. It’s easily to revert these values back to usable values using String.split().
But.. In real life there aren’t ints, but Numbers. The values mostly looks like 452.12070158. I stripped the value, and only use decimals. You don’t actually see the difference when redrawing between 10.04 and 10.042. This saves me a lot of chars too.
Compress it! When saving the file, I push the data into a ByteArray using the bytes.writeUTFBytes() function. I realized ByteArrays can be compressed, so I also use the bytes.compress(); to make the file smaller again. This saves me about 50%! When importing the lines, I used bytes.uncompress(); to make it a normal string again.
This flower is 14kb Import this file in the app to see how I haved drawed it. You can also load it from an url: http://projects.stroep.nl/findClosest/flower2.stroep flower on Flickr
Well this is a next step and I hope to create one day an editor for simple lines and merge this into my artwork process. I think it needs to be more complex but for now this will work. I hope you like it.
I created a useful util-class to make delayed function calling easy. You can make a chain of functions, by adding them with a delay in milliseconds. This chain can be executed multiple times, even in reversed order.
Let’s take a look at a simple example of Chain.
var myChain:Chain = new Chain(); myChain.addEventListener( Event.COMPLETE, onComplete); myChain.add(one, 2000).add(two, 500).add(three, 1000).play(2);
function one():void{trace("one")} function two():void{trace("two")} function three():void{trace("three")} function onComplete(e:Event):void{trace("done.")}
/* trace output: one two three one two three done. */
What is happening here? At the first line we are instantiating the class, and the second line represents what chain does. There is a public function called ‘add’, which is an important part of the class. add(one, 2000) means: execute a function called ‘one’ after 2000 milliseconds. add(two,500).add(three,1000) are functions that are called after one is finished, with other delays. You can create your own rhythm/sequence/pattern. At the end we see play(2), which means: Execute the sequence of functions defined before, and repeat them 2 times. After that, dispatch event COMPLETE.
So that’s basically it. A cool part is you can play it reversed, using playReversed(). I am inspired by jQuery (which has nothing to do with this) to enable the ability to stick functions, but thats optional.
myChain.playReversed(2);
/* trace output: three two one three two one */
Of course you can pauze/continue when you are playing, by calling stop() / doContinue(), and you can determine if it is currently playing using the isPlaying-getter.
These are all the public functions.
/// Constructor publicfunction Chain()
/// Adds a function at a specified interval (in milliseconds). publicfunctionadd(func:Function, delay:Number = 0):Chain
/// Start playing the sequence and calling functions publicfunctionplay(repeatCount:int = 0):void
/// Start playing the sequence reversed publicfunction playReversed(repeatCount:int = 0):void
/// Clears sequence list. Data will be removed. publicfunctionclear():Chain
/// Stop playing, use doContinue to play futher from current point publicfunctionstop():void
/// Continue playing after a stop publicfunction doContinue():Chain
/// Reset indexes publicfunction reset():void
/// Returns the string representation of the Chain private vars. publicfunctiontoString():String
/// Return chain is playing, stopped or completed publicfunctionget isPlaying():Boolean
Hope you like it, let me know if you like to see extra/other related features.
Updates - Private functions are protected - add-functions is now add(function, delay), where function is required. - Class now extends EventDispatcher and play/playReversed dispatches Event.COMPLETE after playing sequence, instead of calling onComplete function - Cleaned up code
I’ve updated my Image class. It is irritating flashsites break the right-click contextmenu. Well, I can’t fix that and Adobe should look at that, but I think it would nice to add some of the browser – features to my image class.
Currently I have these options added to the Image class:
View image Views image in new window/tab. I used NavigateToURL to make this happen.
Save Image as.. Saves image on your computer. I used my ImageClass.saveLocal() to make this happen. This is only available within FP10, but I think this is no problem anymore because < a href = "http://www.adobe.com/products/player_census/flashplayer/version_penetration.html" > 93 % (September 2009) has FlashPlayer 10, so most people have it, and I don’t support outdated software
Copy Image location Copies the url to the clipboard, using System.setClipboard(url). It’s a pity I can’t create a ‘Copy Image’ function, because pushing bitmapdata into the clipboard is only supported in AIR.
Send Image Sends the url to the mail-client, using “mailto:&body=” + src. Also a pity; I can’t add the image directly into the mail.
How to enable the contextmenu:
import nl.stroep.utils.Image;
var myImage:Image = new Image("myImage.jpg"); myImage.enableContextMenu = true; // enable it! this.addChild(myImage);
I still love this class, I use it a lot. I want to encourage you to please add these kind of usability things to your apps / websites. And share them! Yes, it takes some extra time to create/add it, because this IS the finishing touch, but a lot of people will like this kind of features.
Found out something useful, which I’d like to share with you. It’s about calculating the width of menu-items perfectly.
Imaging you are creating a liquid website with a menu. If you want all items to have the same width, you could set the width of each item to totalMenuWidth / items.length. In most cases this will work out. But what is your menu is very small or the items doesn’t fit in that fixed width because the text is too long?
Well you could hardcode the width’s to make your own perfect proportions and spacing, but if your menu is xml-driven and you/someone else adds new menu-items, you have to re-assign the hardcoded widths and you feel unhappy Most hardcoded stuff is evil anyway because it is laziness. (I use it a lot )
Well, I’d like to calculate the perfect scaling menu, so I don’t have to worry the menu will break. You can use the text-length of the menu-item as input for the width calculation. The more letters, the bigger the menu-item, right? So, If you multiply all menu-text-lengths and divide this to the current text-length, you’ll get a ratio which can be divided from the total menu width. I like this theory. So we need to do this in 2 steps; first get the ratios and get the total menu-text-lengths (with a loop), then calculate and apply this on each item. Pseudocode:
This works fine, and its actually very cool. Now we have a function which actually use some proportions to create a liquid menu. After a while I realized that the proportions weren’t really right. If the menu text have odd text-length differences (eg 5 letters vs 25 letters), it looks weird. Larger texts take too much width. I wanted the same proportions kinda like a html-table.
So the menu-items needs to have better proportions. Bigger text should be a smaller and the smaller text should be bigger. After some searching I ‘discovered’ Square root, a.k.a. Math.sqrt() in actionscript. With this function you could ‘normalize’ numbers. Bigger numbers are getting smaller, smaller numbers are getting bigger. This was exactly what I needed!
You can see the result below:
You can see the differences between the menubars and you’ll agree to me that the last one is the best I think this theory could be applied to a lot more things, like graphs or grids.
In case anyone is interested in the code; it can be downloaded here (AS3).
Jackson Dunstan: This is a good way to program for the keyboard by polling rather than by events. Just be sure to keep in mind that a lot of keyboards won't do more th