Posts tagged actionscript 3.0

#quick snippet: Count the days between two dates

0

For a project at work I had to display how many days the visitor of the app had left to still join in on the fun. We had a fixed date (the launch of the project) and a variable date (the date of the day that the project visitor actually visited/used the app). So I was in the need of a script that counts the days between two dates. I know, not that hard, but good to have around nonetheless. Quick snippets for the win!

Anyway, the snippet is pretty clear:

- one variable that represents a day (milliseconds times seconds times minutes times hours)
- two dates turned to milliseconds by “getTime()”
- the difference between those milliseconds

The result of that gets divided by the day in milliseconds and voila: a between days counter!

private function getDaysBetweenDates(date1:Date,date2:Date):int {
	var durationDay:Number = 1000 * 60 * 60 * 24
	var date1InMilli:Number = date1.getTime();
	var date2InMilli:Number = date2.getTime();		    
	var differenceInMilli:Number = Math.abs(date1InMilli - date2InMilli)		    
	return Math.round(differenceInMilli_ms/durationDay);
}

#quick snippet: UNIX Timestamp to as3 Date

0

The problem:
Our flashmovie fetches a Timestamp (UNIX) from some kind of backend code and you need to change this to a workable Date format. It’s actually pretty easy and almost totally standard in flash!


Note:
Flash handles time in milliseconds (think about the timerclass that expects 3000 if you want to time 3 seconds) and the UNIX timestamp is a format based on seconds from the “first day” computers started to use the Gregorian Calendar. In short: the timestamp is defined as the number of seconds elapsed since midnight Universal Time (UTC) of January 1, 1970. Your computer keeps track of how many seconds have elapsed since then and the flash Date class expects this in milliseconds. Simply multiply your seconds with 1000 and you’re done. Easy peasy!


The solution:
A quick code snippet that’s even easy to read for – let’s say – mobile developers!

// replace the capitalized variable with your unix timestamp
// multiply it with 1000 (remember my note above!)
var currDate:Date = new Date(Number(YOUR_TIMESTAMP_HERE)*1000); 
 
// trace out the humanly readable values			
trace(currDate.getDate());
trace(currDate.getMonth());
trace(currDate.getFullYear());



Done!


A real life flash example (DateDisplayer):

Download this wonderful widget here!

Go now, my young actionscript children! Feed on my example and make me proud! Soon the world will be filled with actionscript 3.0 vampires!

basic image gallery #1: circle showcase

0

The intro:
A while ago I made a post about loading images in a grid and an example of how to use the document class. Basic stuff, I know, but it’s a good base to learn/start from.

What I am planning on doing now – I actually already started – is creating a couple of cool ways to display images: basic image galleries. I’m planning on doing a couple so if you have ways that you want me to try out shout them out in the comments.

All galleries will load images out of an xml, so my source files include a custom xml loader. First one up is a circle gallery. All my examples use Tweener for the code animations, so I suggest you download it.

My first example is a circle image gallery by using sine & cosine – that’s Math – which you can see in the preview. The flash file contains alot of comments to explain my actions but it’s really pretty simple once you get the hang of it.


The quick tips:
Flash does not use degrees, but radians. Luckily there’s a simple formula for this:

radian = angle * Math.PI / 180;



The cosine of an angle will give us an x coordinate and the sine of that same angle will give us the y coordinate:

pic.x = Math.cos(radian);
pic.y = Math.sin(radian);



The example:
[kml_flashembed publishmethod="static" fversion="9.0.0" useexpressinstall="true" movie="/blogFiles/gallery_circle.swf" width="530" height="400" targetclass="flashmovie"]

Get Adobe Flash player




The settings:
Inside the xml you can add pictures and choose the radius of the circle.


The aftermath:
You can download the source here. This example is intentionally kept basic but is very versatile and easy to expand. With a little bit of code you can add multiple-page functionality, more animation, maybe even load your flickr account pictures in it with a link to the high-res version! Anyway, the possibilities are endless. Go ahead and try some stuff out! Fly my pretties, fly!

deeplinking with swfadress part II

5

The intro:
Last year I posted some quick codehints for swfadress and I recently noticed they have released a new version. That’s why I, Murten Saerbi, decided to build a small example for all you freeloaders to use and abuse!

This – atleast I think so – is a seriously useful example. I based all my recent websites on this structure and it can pretty much be used as a base for any flash website that utilizes deeplinking. The keys are the “pageHandler” and the “pageClickHandler” functions in the “Main.as” file. I do not consider this as the only way to implement swfAddress but I find it to be a very easy and versatile technique. I would also really like to thank the man with the golden smile Jannes for his tips on this matter of implementing.

Even if you fully master actionscript 3 and the syntax of swfAddress you can seriously benefit from this example as it contains a way to load your main flash with a separate loader and various other interesting techniques.

note: you will need to get acknowledged with Tweener. It’s not obligatory but I use it in the example so it’s best you know what it does. Get it here. I have included it in the project .zip too.


The example:
The example is a .zip file and can be downloaded here. Or wait no, it’s here. Check an online example of it over here.


The aftermath:
As you can see installing swfadress in a website is no hard work. Having it in a website is even really helpful for your visitors (SEO, direct-page-link, …)!

I can’t really think of a reason that makes you NOT want to include it in your website UNLESS you like dialogs like these:

T. Anthoni Luvs his BabYSt4hr * ElVeS 4-EVAH!:
OMG MURTEN!!!111 LOL!
Murten Saerbi:
What?
T. Anthoni Luvs his BabYSt4hr * ElVeS 4-EVAH!:
Go to www.somepagehere.com then click “about” then “link” then “Tom”
T. Anthoni Luvs his BabYSt4hr * ElVeS 4-EVAH!:
Then click “about Tom” then “personal” then “info” then “contact”
T. Anthoni Luvs his BabYSt4hr * ElVeS 4-EVAH!:
Then click “contact Tom” and you can contact me!

Then you should totally don’t do it. Elves 4-evah!

#quick snippet: using the textformat to style textfields

1

The intro:
Text that has been sent to a database by using “htmlText” instead of plain “text” has certain properties given with it such as ‘color’, ‘font’, etc… . Let’s say you push htmlText into a database and want to read it out in the frontend but you don’t want it to have that saved style. That’s where the textFormat class comes in.


The code:
It’s actually pretty simple once you get the hang of it. First of all you need to add your font to the library. You can do this by clicking on the small arrow with the three lines on the top right of the library panel:

fontscreen screenshot


In the menu that pops up you need to select the option “new Font…”. A box appears where you can set your font, fontname, style and size. By clicking “ok” you can see the font getting added to the library. Right-click it and give it a linkage name you can remember. I will use “Futura”.

From now on it’s just a few lines of code. Import the TextFormat class and if “automatically declare stage instances” is unchecked the font at the top of your class:

import flash.text.TextFormat;
import Futura;


Make an instance of your fontclass and an instance of the TextFormatClass and fill in the properties you want:

var fontFutura:Futura = new Futura();
 
var titleformat = new TextFormat();
titleformat.color = "0x000000";
titleformat.size = 12;
titleformat.font = fontFutura.fontName;


Finally set the textFormat of your textField to the newly created one:

textfield_txt.setTextFormat(titleformat);


Boom. Done.

#quick snippet: right-click menu in as3

0

The intro:
I noticed a friend of mine always builds in a custom right-click menu in his flash websites and decided that this is an excellent code snippet to share with you boys and girls.


The code:
It’s actually pretty simple so here’s the full block. Additional tips are given in actionscript comment style.

// create a new instance of the ContextMenu class
var my_instance:ContextMenu = new ContextMenu();
 
// hide the standard items
my_instance.hideBuiltInItems();
 
// create a new ContextMenuItem by feeding the constructor a piece of text
var menuItem_instance:ContextMenuItem = new ContextMenuItem("made by crazy beaver");
 
// maybe you even want one that has a link behind it
var menuItem2_instance:ContextMenuItem = new ContextMenuItem("crazy beaver");
// add a listener to this item
menuItem2_instance.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, clickHandler);
 
// push all your menuItems in the ContextMenu instance
my_instance.customItems.push(menuItem_instance, menuItem2_instance);
 
// set the default ContextMenu for your movie to your own contextMenu
this.contextMenu = my_instance;

Don’t forget to create a handler for the items that have listeners to it (in this case “menuItem2_instance”) like so:

private function clickHandler(e:Event):void {
trace("you clicked on the crazy beaver link!");
}

It’s a small snippet, but it’s a nice feature to have and definately worth to implement in your future projects!

Comparing data in actionscript 3.0

0

The problem:
Say we need to compare an xml file containing some months to a list of all the months so we can get their corresponding monthNumber (January = 1,  February = 2, …).

First of all we will need a list of months. I decided to go for a multidimensional array with the monthNumber in it aswell:

var monthLabels:Array = new Array([1, "January"],[2, "February"],[3, "March"],
[4, "April"],[5, "May"],[6, "June"],[7, "July"],
[8, "August"],[9, "September"],[10, "October"],
[11, "November"],[12, "December"]);



Then we need another file (which can be strings a user fills in or – in my case – an xml file) to compare data with:

<xml>
<month name = "January">some text</month>
<month name = "Februari">some text 2</month>
<month name = "December">some text 3</month>
</xml>



And here is the code, it’s almost so easy that even flash-for-mobile developers can understand it (for all you mobile developers -> the explanation follows):

for(var i:int = 0; i < xml.month.@name.length(); i++) {
	for(var u:int = 0; u < monthLabels.length; u++) {
		if(xml.month.@name[i] == monthLabels[u][1]) {
			trace(monthLabels[u][0]);
		}
	}
}



The explanation:
First of all we loop through the amount of monthnames (the first for loop). That loop traced out will give us all the monthnames in our file or string (in my xml example 3, being “January”, “February” and “December”).
For each result of that first loop we loop through the monthLabels array’s length. There are 12 months so I could have used “12″ but I use length instead so you can use the code for other data aswell.

In that second loop we check if the value currently being processed by the first loop (xml.month.@name[i]) is equal to one of the values in our array. Since we have a multidimensional array we need to specify which value we want to use to compare with. The month name is on the second place so I use “1″ to identify that place (arrays are zero-based so 0 = first place, 1 = second place). If we have a match the if will succeed and we trace out the corresponding number.

This particular example will trace out:

1  // Which is the monthNumber for January
2 // Which is the monthNumber for February
12 // Which is the monthNumber for December

I hope this helps you multidimensional-and/or-comparing-data troubled kids out!

Actionscript 3.0 email validator

0

A quick email validator snippet. I know it’s not much but it sure is useful!

private function isValidEmail(email:String):Boolean {
var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
return emailExpression.test(email);
}

“Use it, abuse it!” Like Arcko Drazen would say.

free ‘widget’: logo switcher/promo switcher

0

Aside from the fact that I am still alive there is also another great thing: free widget!

I made this widget to show how relatively easy it is to make dynamic flash widgets. This one is controlled by an xml where you can input:

- text
- images
- borderthickness
- bordercolor
- backgroundcolor
- switch speed (time that determines how fast it goes to the next promo)
- url (the website that opens when you click the logo)
- clickTarget (choose in what window it opens: _self, _blank, … Empty tag means _self)
- shine (choose if you want the shine or not, values are true OR false)

You can ofcourse implement hundreds of other parameters if you want, but being just a simple promo switcher 9 should be enough.

PS: if the text part is ommited the logo will slide to the middle of the widget.

Check it out:

You can check out the xml by clicking here.

DOWNLOAD INSTRUCTIONS

There is a “bin” folder inside the .rar which contains all files to be uploaded (.swf, js, images, xml) and an example of an html with swfObject and a few parameters to set (xmlpath, imagepath).

Download it here!

Skinning a combobox component in actionscript 3

5

A quick post in relation to my post about embedding fonts in actionscript 3 components: A combobox example. I have prepared a quick example that you can see below, I’m sure you guys and girls can come up with a design that suits your needs.

You can check out the code below or download the example file.

// create a new textformat and set the style of it
var myFormat : TextFormat = new TextFormat();
myFormat.font = "Cooper Std Black";
myFormat.color = 0xffffff;
myFormat.size = 13;
myFormat.indent = 4;
 
// apply the textformat and embed fonts for the selected option
first_cb.textField.setStyle("textFormat", myFormat);
first_cb.textField.setStyle( "embedFonts", true);
 
// apply the textformat and embed fonts for the dropdown textfields
first_cb.dropdown.setRendererStyle("textFormat", myFormat);
first_cb.dropdown.setRendererStyle("embedFonts", true);


Go to Top