Archive for the 'flash' Category

28JanMy first Adobe Air Application

To help improve my AS3 skills I thought a good starting project would be to challenge myself to create an Adobe Air desktop application, and after working on a Christmas countdown, I decided it would be rather nice to make a Countdown timer.

This article runs through a few things I had to learn in AS3 to create it.

Getting Adobe Air working

First thing I needed to do was ensure that Adobe Air was installed and that everything working.

  • Install Adobe Air
  • Ensure Flash is updated, and install all the available updates. For Flash CS4 they are here.
  • Get the Adobe AIR SDK. Once downloaded this needs to be copied into the AIK folder in the Flash program folder – i.e. C:\Program Files\Adobe\Adobe  Flash  CS4\AIK.

Phew! Now creating the application…

First step was to get an accurate countdown mechanism. I found this Countdown example which was a good starting point to create a Countdown class in AS3. The basic idea is that it takes the current date and the specified event date then works out the difference.

Creating the event date input

I used Flash UI components for the drop down menus, but controlled their content using my Countdown class. To style the UI combo box component you can edit it in the FLA file, but to change the font you need create a TextFormat variable, then apply it to the component.

var comboFont : TextFormat = new TextFormat ();
comboFont.font = "Calvert MT Light";
comboFont.color = 0x333333;
comboFont.size = 12;
eventDayCombo.textField.setStyle ("embedFonts", true);
eventDayCombo.textField.setStyle ("textFormat", comboFont);
eventDayCombo.dropdown.setRendererStyle ("embedFonts", true);
eventDayCombo.dropdown.setRendererStyle ("textFormat", comboFont);

I then added data to the combo box. It is important to add this data dynamically to ensure that the Countdown is always up to date.

eventDayCombo.addItem ({label: dayStr, data: day})

Reading, saving and using XML data

Check if the data exists

Every time the application opens it checks to see if the user has already set an event date. The first thing it does is specify the name of the file, then where this file should be located. In my Countdown example the application creates an XML file called CountdownPrefs in the user’s My Documents folder.

var prefs:String = "CountdownPrefs.xml";
var prefsFile:File = File.documentsDirectory.resolvePath (prefs);

To check if a file exists on the system you can use prefsFile.exists; this will give a true or false result.

if (prefsFile.exists){

AS3 uses file streams to manipulate data; this makes the process much simpler than in AS2. It opens a file stream and reads the data. When it has completed reading the data the event listener calls the function processXMLData.

readStream = new FileStream ();
readStream.addEventListener (Event.COMPLETE, processXMLData);
readStream.openAsync (prefsFile, FileMode.READ);
}

Processing the data

So, to process the XML data I just use the function to specify the data then close the file stream. Now I can set my event date from the data in the XML file.

function processXMLData (event : Event) : void {
var prefsXML: XML = XML (readStream.readUTFBytes (readStream.bytesAvailable));
readStream.close ();
TITLE = prefsXML.child ("title");
YEAR = prefsXML.child ("year");
MONTH = prefsXML.child ("month");
DAY = prefsXML.child ("day");
HOUR = prefsXML.child ("hour");
MINUTE = prefsXML.child ("minute");
startCountdown ();
}

Saving new data

When the user sets their event date in the application it creates an XML file. First I defined what the content of the XML should be.

var dateStr:String = "<?xml version=\"1.0\" encoding=\"utf-8\"?><countdown><title>" + TITLE + "</title><year>" + YEAR + "</year><month>" + MONTH + "</month><day>" + DAY + "</day><hour>" + HOUR + "</hour><minute>" + MINUTE + "</minute></countdown>";

It then opens a file stream and writes the data to the location specified previously using the string variable to construct the XML content.

var newStream:FileStream = new FileStream();
newStream = new FileStream();
newStream.open(prefsFile, FileMode.WRITE);
newStream.writeUTFBytes(dateStr);
newStream.close();

Delete the data

To reset the countdown application all you need to do is simply delete the XML file then I called my reset function to restart the application.

if (prefsFile.exists){
prefsFile.deleteFile ();
resetCountdown ();
}

Using the Timer Class

So my Countdown function returns an object with the years, months, days, hours, minutes, seconds and milliseconds, then to update my countdown display I need to repeat the call every millisecond.   I can use the Timer class to repeat the function call and get the updated countdown object.

timerObject:Timer = new Timer (delay, repeatCount );
timerObject.addEventListener (TimerEvent.TIMER, updateCountdown);
timerObject.start ();

The finishing touches

Creating a custom chrome

To make the application visually nicer I added my own chrome to it with minimise and close buttons, here is how: http://www.adobe.com/devnet/air/flash/articles/custom_chrome_app.html

Creating an application icon

This is very simple. All you need to do is create little image files in the sizes: 128×128, 48×48,32×32, 16×16 then on the publish settings you can add the icon images.

Publishing the application

All you have to do then is publish the application and it’s ready to go. Look out for my next post if you want to download the application and try it out.

07DecCreating Buttons with ActionScript 3.0

This is a quick guide on how to create and set up a button in AS3.

Set up the movie clip as a button

To make sure that your movie clip will act like a button you need to set the buttonMode and also set the movie clip to have a hand cursor.

bttn.buttonMode = true;
bttn.useHandCursor = true;

Ensure that you won’t interact with the child movie clips

When you rollover a movie clip in AS3, then the mouse cursor will recognise child clips within your button movie clip. To ensure that this doesn’t happen you can set the mouseChildren to false.

bttn.mouseChildren = false;

Making the button do stuff

Create a event listeners to call a function when the you interact with the movie clip.

bttn.addEventListener (MouseEvent.MOUSE_DOWN, doStuff);
bttn.addEventListener (MouseEvent.MOUSE_OVER, overBttn);
bttn.addEventListener (MouseEvent.MOUSE_OUT, outBttn);

Using mouse events

Here is a sample of how you use the mouse events. This function will trace the movie clip that you have clicked on.
function doStuff (evt : MouseEvent) : void
{
trace(evt.target)
}

05SepNice banner from Auto Trader

I was just doing some browsing on IMDB this afternoon and saw this banner. I don’t normally even want to click on interactive banners, but was rather intrigued…

Frame 1 – Draw a car you’d like to sell

Banner - First frame

Frame 1 – My wonderful drawing

Yes – my car actually does look like that – isn’t it lovely. Erm…
Banner - Second Frame

Frame 2 – Cheeky robot

Hard to believe this was actually my fourth or fifth attempt at drawing a decent looking car. He actually had a few different cheeky messages. He even fell over laughing once.
Banner - Third Frame

Frame 3 – Are you done?

Cute little jumping up and down animation on the Drive button. I liked the call to action on this too, made me want to click on it.

Banner - Fourth Frame

Frame 4 – Interact a wee bit more

I dislike when interactive banners want you to something, but it does actually seem connected to the rest of the banner. This is a nice way to make you feel like drawing the car actually had a point.
Banner - Fifth Frame

Frame 5 – Aw, he’s actually going to drive it away

So off he goes in to the distance, and I get taken to the landing page: http://www.autotrader.co.uk/CARS/selling/selling_a_car.jsp?platform=DFA
Banner - Sixth Frame

Well, cute little banner that I liked. Fun to use, nice touches…and maybe when I am selling my car I’ll even go to Auto Trader.

26JunDipping my toes into Flash CS4 and AS3

Well, I downloaded the Flash CS4 trial and have been experimenting with it for a day or so.

Overall I’m positive about what I’ll be able to do with the AS3, but a little disappointed in Flash CS4. I’ve never been that excited about the fancy new features in it, although I’m sure I will end up finding them useful. What my problem is, is that there was a few things about the interface and set up that I’d hope they would have improved.

The main one is the colour palette. You still can’t save swatches or custom colours. How annoying! It is also irritating that the ‘Free Transform’ and ‘Gradient Transform’ tools are together – it does get frustrating having to click between them when you are doing a lot of resizing and colour shading.

I have struggled a little today with AS3, but I think a good sit down reading ‘Learning ActionScript 3.0′ will probably let me understand better how it’s structured, then it will be a lot easier to make the transition from AS2 – I’m already am quite fond of the event listener.

04JunActionScript Naming Conventions

Well, in the midst of the Flash interactive feature I’ve been working on, I decided it really was about time I set myself a naming convention to follow when writing Actionscript code. I’ve always been a bit haphazard about how I name things, which in the long run will make it difficult for someone else to understand or to re-use. I also need to remember to use descriptive names for things. This will make it much easier for someone else reading the code to understand what each thing is or what it is doing.

Anyway, this is probably a work in progress, but at least I’ve gotten started!

Read more here: Abobe ActionScript 2.0 Best Practices – Naming Conventions

So, here it is:

Classes

  • Start with Uppercase
  • Concatenate words, using mixed cases

class MyClass

Functions & Objects

  • Start with lowercase
  • Concatenate words, using mixed cases

function myFunction

Movie Clips

  • Prefix with ‘mc’
  • After prefix start with Uppercase
  • Concatenate words, using mixed cases

mcMyMovieClip

Constants

  • All uppercase
  • Separate words should contain underscores
  • MY_CONSTANT

Number variables

  • Prefix with ‘num’
  • After prefix start with Uppercase
  • Concatenate words, using mixed cases

numMyNumber

String variables

  • Prefix with ’str’
  • After prefix start with Uppercase
  • Concatenate words, using mixed cases

strMyString

Arrays

  • Prefix with ‘arr’
  • After prefix start with Uppercase
  • Concatenate words, using mixed cases

arrMyArray

Boolean expressions

  • Prefix with ‘is’
  • After prefix start with Uppercase
  • Concatenate words, using mixed cases

isThisOn

05FebFlash Tutorial – Arranging a scene (Part Two) using hitTest

In the first tutorial (Arranging a scene using depths & scale) I created a scene that gives the impression that a character can move around scenery using the _y property. This tutorial explains how to stop the character moving through the scenery using hitTest.

First, create the file from the first tutorial.

In the Scene

Create a new movie clip and add a rectangular shape in it. Place this movie clip in each of your character and scenery movie clips, re-sizing it to the width of the item and the height to represent the “depth” – see diagram. Name each of the rectangular movie clips “testarea” and set the alpha to 0%.

Flash tutorial diagram

Initial Variables

Add this below the intial variables in the Actions frame.

moveAllowed = true;

Additional Code

In the mouseListener function, replace the code

_root.Character._x = _root._xmouse;
_root.Character._y = _root._ymouse;

with this code

if (_root.moveAllowed) {
_root.Character._y = _root._ymouse;
_root.Character._x = _root._xmouse;
} else {
_root.Character._x = _root._xmouse;
}
for (i=0; i<DepthArray.length; i++) {
if (_root.DepthArray[i].mcname != "Character") {
if (_root.Character.testarea.hitTest(_root[DepthArray[i].mcname].testarea)) {
_root.moveAllowed = false;
break;
} else {
_root.moveAllowed = true;
}
}
}

And so…

Here are the results

05Decokay, it’s December, I can do Christmasy posts now

Way back on November the something-th (I think when they were putting the Christmas lights on) there were actually reindeer on Buchanan Street, yes – real reindeer – I’m sure you’re as excited as I was! Anyway – I (along with all the other losers) took a picture on my phone…

REINDEER!!!!!!!!

And, while I’m on the subject, a few years ago I created a little reindeer Christmas game to teach myself more ActionScript. It’s a bit silly, but I’ve cleared the hi-scoreboard anyway if you want to have a wee go.

Christmas Reindeer Game

21NovFlash Tutorial – Arranging a scene using depths & scale

This tutorial explains how to use ActionScript to update depths and scales to give the impression that a character can move around scenery using the _y property.

First of all create your graphics and place them where you want them on the scene, giving them individual names. Ensure that the registration point is set to the bottom of the movie clip, this is especially important if your movie clips are different heights.

Next, create a new layer. This is where all the actions will go.

Initial variables

The first actions will hide the mouse cursor and state the initial variables; these will set the increments of the scale and y position.

Mouse.hide();
MinScale = 50;
MaxScale = 100;
ScaleIncrements = (MaxScale-MinScale)/100;
MinPos = 10;
MaxPos = 250;
PosIncrements = (MaxPos-MinPos)/100;

Setting the scene

Then, create an array to store all depth and height information on all the movie clips on the scene. This is a multidimensional array that stores the movie clip name, it’s _y position and the current depth.

var DepthArray:Array = new Array();
DepthArray.push({mcname:"Scenery_1", mcposition:Scenery_1._y, mcdepth:Scenery_1.getDepth()});
DepthArray.push({mcname:"Scenery_2", mcposition:Scenery_2._y, mcdepth:Scenery_2.getDepth()});
DepthArray.push({mcname:"Scenery_3", mcposition:Scenery_3._y, mcdepth:Scenery_3.getDepth()});
DepthArray.push({mcname:"Character", mcposition:Character._y, mcdepth:Character.getDepth()});

Next, the array should be sorted based on the y position. The property “Array.NUMERIC” is used to ensure the sort is ordering the array as a number rather than a string.


DepthArray.sortOn(["mcposition"], Array.NUMERIC);

Then the movie clips on the scene should be updated. This uses a for loop which will go through all the items in the array, and update the movie depth according to the order they have been placed into within the array, then scale the movie clips according to their y position so the movie clips that are higher will be smaller. This uses the variables that have been set at the beginning.


for (i=0; i<DepthArray.length; i++) {
// sort initial depths
DepthArray[i].mcdepth = i;
_root[DepthArray[i].mcname].swapDepths(DepthArray[i].mcdepth);
// set inital scales
CurrentPosition = (_root[DepthArray[i].mcname]._y-MinPos);
CurrentPositionPerc = CurrentPosition/PosIncrements;
_root[DepthArray[i].mcname]._xscale = _root[DepthArray[i].mcname]._yscale=MinScale+((CurrentPositionPerc)*ScaleIncrements);
}

Time to get moving

So now a mouse listener is added to allow the scene to be updated you move the character around.


var mouseListener:Object = new Object();
mouseListener.onMouseMove = function() {

The mouse cursor has already been hidden as part of the initial actions, so now the character must be set to follow the x and y positions of the mouse.


_root.Character._x = _root._xmouse;
_root.Character._y = _root._ymouse;

The array must be updated to set the character at the right depth, and then the scene is updated according to this.


for (i=0; i<DepthArray.length; i++) {
DepthArray[i].mcposition = _root[DepthArray[i].mcname]._y;
}
DepthArray.sortOn(["mcposition"], Array.NUMERIC);
for (i=0; i<DepthArray.length; i++) {
DepthArray[i].mcdepth = i;
_root[DepthArray[i].mcname].swapDepths(DepthArray[i].mcdepth);
}

Now the correct scale for the character is set.


CurrentPosition = (_root.Character._y-MinPos);
CurrentPositionPerc = CurrentPosition/PosIncrements;
_root.Character._xscale = _root.Character._yscale=MinScale+((CurrentPositionPerc)*ScaleIncrements);
};

Finally you just activate the listener


Mouse.addListener(mouseListener);

And so…

So, now just take a look at the final results.

21OctBad Flash Programming – Case Study

Way back in 2003, when I was just starting to seriously work with Flash, I was inspired by the vast array of games popping up on the internet to create my own, making a slight nod to the sci-fi genre, and computer games from my childhood including Monkey Island and the lesser known, but very cool, Omnicron Conspiracy.

This was my first attempt at any kind of serious ActionScript programming, so now with ActionScript 3.0 on the horizon I’m now going to deconstruct why it was all really not very good.

Organisation and Naming

The main reason to organise your file is to make it easy for yourself and others to work with, make changes, and return to at a later time to make updates.

Layers

Flash - Layers

So here’s a little snapshot of my FLA file. I’ve made some attempt at naming layers, even categorising them, but I’ve been a little lazy and missed some out. This is going to make it quite difficult if I want to change something on a specific layer. If I’d carefully named all my layers with an appropriate and consistent naming convention, then put them into relevant folders, searching for things would be a much easier process.

Library

Flash - Library

It’s not just in the layers section that setting naming conventions and organising folders is helpful. As you can see in this screen of the library I’ve named the symbols with some relevant names, but there is no naming conventions or organisation, which again is going to make it difficult to find a specific symbol I’m looking for.

Actions & Functions

Flash - Actions

Right, now the really crazy part of the programming. See all those little a’s, I’ve put code in every frame, and on quite a lot of the layers. Many of these are also repetitions of what was on the frame before. There is also code on symbols within the stage. If I want to find out what is happening within the programming I’ll pretty much have to read through almost all of these frames and layers, even then I’m going to have to decipher how it all works. So, to make the application easier to work with, I would be better doing the following:

Actions

Placing all the actions on the one layer makes the code easy to find and debug, this is especially helpful if you are creating a complicated application. You can also create a separate ActionScript (AS) file to keep all your actions together.

Functions

According to Flash…

A function is a script that you can use repeatedly to perform a specific task. You can pass parameters to a function, and it can return a value.

This means I can create one piece of code that I can use once, or be called again using one line of code, instead of repeating the full code each time. So, if I’d created functions for certain repeated tasks, there would be less code throughout the file, and it would be a more streamlined file to work with.

See the example below:

Use this, once:


check_money = function () {
  this.onEnterFrame = function() {
    if (_root.moneyAmount == 0) {
      _root.moneyHave = 0;
    } else {
      delete this.onEnterFrame;
    }
  };
};

And whenever you want to use the function use:


check_money();

Instead of the following on every frame within the layer:


if (_root.moneyAmount == 0) {
  _root.moneyHave = 0;
}

Structure, Timeline & making it all Dynamic

Flash - Timeline

Another thing that makes my FLA file very messy and difficult to amend is that everything is placed along the timeline. Each background tile and line of conversation has all been placed on each frame. All movements are animated in movie clip within movie clip. This makes the file very rigid and time consuming to develop, as each item is fixed.

Changing the Scene

Using the attachMovie() function means I could store each scene in the library then load them in as needed.

Movement

Instead of animating the character along each path I want him to take I could create one movement function, then every time I wanted him to move I could just call the function including the coordinates for where he should stop.

Dynamic Text

With dynamic text I could create functions to control the lines of conversation and their consequent actions, rather than place different static text on every scene.

Which means…

Creating an application in this way creates:

Increased flexibility – It would allow amendments and additions to be made easily, making developing the application a smoother process.

Increased transferability – The code can be reused again and again in other applications, saving time and effort in the future.

End results

Just to keep you a little longer, here is the flash game, still a bit buggy and rather cheesy. I always meant to create a next chapter for it and develop it further, but hopefully you’ll enjoy it anyway.

PLAY Escape from Zeixo

08OctFlash banner ads

Click here. Click here. Click here.

The general inclination of a user is to ignore banner ads. We are far more cynical about online marketing now, so, if the main aim of an ad banner is to engage users, increase the clickthrough rate and increase brand awareness then the banner should be more than just relevant content and pretty animations.

Recently I’ve seen a great banner for the Worldwide Wildlife Fund. It requests:

Can you spot the tiger?

using a set of binoculars, which zooms in on the forest background, but after a few seconds of trying (and failing) the message pops up

Difficult, isn’t it

Then it prompts you to click to adopt a tiger while you still can. I mean, I would, but my flat’s too small, and my current feline occupants probably wouldn’t be too happy about it – but basically I liked it; it creates awareness of their campaign in a clever and engaging way, while appealing to the user to click.

We have the skills to create innovative interactivity in a banner that will capture the user’s interest, but there are a few things I think are required to make this happen.

Awareness – a greater awareness by everyone involved in the project of what can be achieved, using the available technology and subsequent timescales, will mean a smoother process and a more effective outcome.

Research – If we spend more time considering who is the target market, what are their interests, what would capture their attention and therefore make them click on the banner, then we are a step closer to creating an effective ad.

Concept creation - time spent on producing clever and appealing banner concepts should not just involve the design department; Marketing and account management have very valuable input on how we could achieve successful banners.

If at first you don’t succeed, refer to the instruction manual

Paul’s post got me thinking about best practices for the Flash banners we create.

Adobe’s provided some basic instructions on building banners – Adobe Flash Best Practices – Advertising with Flash

I think we should take it a step further and, to a certain extent, standardise how we build banners. I’d like to consider the points below, and get some feedback/comments from everyone.

Optimum frame rate
Considering likely computer performance, resultant file size, as well as appearance, how many frames per second should we create the file at?

(I’m just going to copy this in from an email Paul sent round)

“About magic frame rate numbers: Recommended fps values for your FLA document are either 21 or 31, otherwise known as the “magic frame rate numbers”. The reason for these values is that the default document setting of 12 fps is more often than not too slow for tween animations, resulting in “jerky” motion. So most of the time it needs to be higher. In addition, it has been found that two SWFs published to the same fps, will run slower on the Mac Flash Player than on the PC Flash Player, given equivalent processing power. Sometimes the lag time is quite noticeable. To counteract this “bug”, we must set our FLA to either 21, 31, 41, 51 or 61 fps to negate this effect. But of course most computer processors cannot keep up with a frame rate higher than 31 fps, or performance issues in the Flash Player may occur. Thus it is advised that only frame rates of either 21 or 31 be used for most FLA documents. Only if you are running an FLV video player in your browser with the video at high resolution (larger than 320×240) would it be advisable to drop the frame rate of your FLV down to 12-15 in order to conserve performance. See Tom Green’s CMX article for more details on video performance in Flash.”

Taken from: http://www.communitymx.com/content/article.cfm?page=2&cid=C1379

Animation length
What is the average amount of time a user spends on the page, and how should we translate this to the length of the banner ad? I think IAB recommends 15 seconds for the length of the animation – IAB Rich Media Standards

Duration of each message
On average how many seconds does it take a user to read the message on a banner ad? I normally make this 3 – 4 seconds, but deciding on a value would ensure consistency throughout all the Flash banners and animated gifs we create.

cliiiiiiiiiickTaaaaaaaaaaaaaaaaaggggg

Okay – and then there’s the ‘clickTag’…(cue dramatic music). It’s quite simple…..we set the button action in the flash to go to the simple value ‘clickTag’

Kind of like this:

on (release) {
getURL(clickTag, "_blank");
}

So, when the flash is embedded in the page, the page then tells flash what this ‘clickTag’ value should be, i.e. the correct URL with all the tracking bits and pieces added. Another thing to be aware of is which format of ‘clickTag’ should be used; The majority of times the ad server network requests ‘clickTag’ be used, however ‘ClickTag’, ‘ClickTAG’ and ‘clickTAG’ are also used.

Oh, and another thing

One thing that can cause problems when creating the banners, and make it a more time consuming process, is not having the full technical information right from the beginning; Where are the banners going? What are the file size limits? What are all the dimensions required? What is the clickTag format? etc.

If all departments work together from the beginning to verify all the information required this will cause less problems and changes after the banners have been built.

Anyway…

I’ve waffled on for quite a wee bit now, but hopefully this is a step in the right direction for us to continue discussing how to improve our processes to create effective online ads.




What I'm Doing...

Posting tweet...

Powered by Twitter Tools.

Blogroll

Recent Listening