Archive for the 'ActionScript 3' Category

04th Sep 2008

Tween Sequencer

Many of the projects I have done have included creating some sort of repeating sequence of tweens. In my early projects I would trigger the next tween using the finished event for each tween. This sucked.

So recently I had some time and decided to take a crack at creating a tween sequencing class. Basic idea being that I add a sequence of tweens to a object and then just call a start function to trigger the sequence.

My first idea was to create a collection of tween objects and store references to them in an array. This led me to com up with this:

package com.vfd.animation.tweens{
import fl.transitions.TweenEvent;
import fl.transitions.Tween;
public class TweenSequencer {
private var _tweens:Array=new Array ;

private var index:Number=0;
public var loop:Boolean=false;
public function TweenSequencer() {
trace(”New Tween Sequencer”);
}
public function addTween(tween:Tween):void {
tween.stop();
tween.addEventListener(TweenEvent.MOTION_FINISH,nextTween);
this._tweens.push(tween);
}
public function removeTween(tween:Tween):void {
for (var i:Number=0; i < this._tweens.length; i++) {
if (this._tweens[i] == tween) {
this._tweens[i].removeEventListener(TweenEvent.MOTION_FINISH,nextTween);
this._tweens.splice(i,1);
break;
}
}
}
public function start():void {
this.startTween();
}
public function stop():void {
this.pause();
this.reset();
}
public function pause():void {
if (this._tweens[this.index]) {
this._tweens[this.index].stop();
}
}
private function nextTween(event:TweenEvent):void {
trace(”Index before ” + this.index);
trace(”Loop : ” + this.loop);
this.index++;
if (this.loop && this.index >= this._tweens.length) {
this.reset();
}
trace(”Index after ” + this.index);
this.startTween();

}
private function startTween() {
if (this._tweens[this.index]) {
this._tweens[this.index].play();
} else {
this.reset();
}
}
private function reset():void {
this.index=0;
}
}//end class
}//end package

The basic idea worked, but I ran into a couple of problems. I was testing this with a basic ball. I placed the ball in the top right corner of the screen. Every time I ran the thing it would play the tweens in the correct sequence, but the ball always started in the bottom right corner of the screen making the first run through the sequence incorrect. However, after the first run through it played as expected.

This took me a while to figure out, but as it turns out that when I created the tweens, even though I immediately stopped them, it was setting the properties of the ball to the start values of the second set of tweens that were applied to the x and y coordinates.

I tried all sorts of variations including writing my own tween class that overrode the starting behaviors of the standard tween class and I still ended up with the same results (though it is entirely possible that I missed something simple).

I did turn out that if I explicitly set the x and y coordinates of the clip after creating the tweens, it worked as expected. However, I was only testing with many tweens applied to one object. If I was applying tweens to multiple objects I would have to reset all of them and having to explicitly set the coordinates defeated the purposes of placing them on the stage where I wanted them to begin with. Additionally, I ran into this problem with tweens applied to x and y, but if there are other properties that behaved the same way, I would have to reset those as well. This class was intended to make this process sequencing tweens easier, not simply introduce a new set of headaches.

After some time I came up with the idea of using a single tween inside of the sequencer class. Instead of storing multiple tween instances, I would just store sequence of properties and values that I wanted to tween an update the single tween instance. this would keep the tweens property settings from conflicting with one another and throwing the sequence off. This lead to:

package com.vfd.animation.tweens{
import fl.transitions.TweenEvent;
import fl.transitions.Tween;
import flash.display.Sprite;
public class TweenSequencer {
private var _tweens:Array=new Array();
private var tween:Tween;
private var index:Number=0;
public var loop:Boolean=false;
private var placeHolderSprite:Sprite = new Sprite();
public function TweenSequencer() {
trace(”New Tween Sequencer”);
this.tween = new fl.transitions.Tween(this.placeHolderSprite,”alpha”,null,1,1,1,true);
this.tween.stop();
this.tween.addEventListener(TweenEvent.MOTION_FINISH,nextTween);
}
public function addTween(obj:Object, prop:String, easing:Function, begin:Number, end:Number, duration:Number, useSeconds:Boolean = false):void {
this._tweens.push(arguments);
}
public function start():void {
this.startTween();
}
public function stop():void {
this.tween.rewind();
this.reset();
}
public function pause():void {
this.tween.stop();
}
private function nextTween(event:TweenEvent):void {
this.index++;
if (this.loop && this.index >= this._tweens.length) {
this.reset();
}
this.startTween();

}
private function startTween() {
this.tween.stop();
if (this._tweens[this.index]) {
this.tween.obj = this._tweens[this.index][0];
this.tween.prop = this._tweens[this.index][1];
if (this._tweens[this.index][2] is Function) {
this.tween.func = this._tweens[this.index][2];
}
this.tween.begin = this._tweens[this.index][3];
this.tween.finish = this._tweens[this.index][4];
this.tween.duration = this._tweens[this.index][5];
this.tween.useSeconds = this._tweens[this.index][6];
this.tween.start();
} else {
this.reset();
}
}
private function reset():void {
this.index=0;
}
public function reverse() {
this._tweens.reverse();
}
}//end class
}//end package

So now this:

import com.vfd.animation.tweens.TweenSequencer;
var ts:TweenSequencer = new TweenSequencer();
ts.loop = true;
ts.addTween(ball, “alpha”, null, 0,1,2,true);
ts.addTween(ball, “x”, null, 130,300,2,true);
ts.addTween(ball, “y”, null, 130,300,2,true);
ts.addTween(ball, “x”, null, 300,130,2,true);
ts.addTween(ball, “y”, null, 300,130,2,true);
ts.addTween(ball, “alpha”, null, 1,0,2,true);
ts.start();

Produces this:

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, OOP, Open Source Projects Comments 1 Comment »

15th Aug 2008

Hold on a Second

You can find a lot of tween libraries for AS2 and AS3. Many of these include some sort of mechanism for delaying the start of a tween. A while back I took my own shot at this based off of another class that I found and came up with:

import mx.transitions.Tween;
class com.vfd.animation.tweens.DelayedTween extends Tween{

private var intervalID:Number
private var delay:Number = 0;

public function DelayedTween(object, property, easingFunction, start, end, duration, useSeconds, delay) {

super(object, property, easingFunction, start, end, duration, useSeconds);
this.delay = Math.abs(delay*1000);
this.setDelay();

}
private function start() {

}

private function setDelay() {
if (this.delay > 0) {
this.intervalID = setInterval(this, “startAnimation”, this.delay);
}else {
this.startAnimation();
}
}

private function startAnimation() {
clearInterval(this.intervalID);
super.start();
}

}

This was more or less a simple copy of the class I had found. I got a chance to look at this again today and realized I could simplify it a bit. I ended up with:

/**
* @author Jeremy Wischusen
* This class allows for a delay before starting the animation.
*/
import mx.transitions.Tween;
import mx.utils.Delegate;
class com.vfd.animation.tweens.DelayedTween extends Tween {
/*
Holds the number of seconds to wait before starting the animation.
*/
private var _delay:Number = 0;
/*
Instance variable holding a reference to the start function of the Tween class.
This is needed due to scoping issues when using setTimeout.
*/
private var superStart:Function;
public function DelayedTween(object, property, easingFunction, start, end, duration, useSeconds, delay) {
this.delay = delay;
/*Use the Delegate class to create a reference back to the tween start funciton
that can be used with setTimeout. */
this.superStart = Delegate.create(super, super.start);
super(object,property,easingFunction,start,end,duration,useSeconds);
}
/*Override the default start function so that the delay can be applied.*/
public function start() {
if (this._delay>0) {
_global.setTimeout(this.superStart,this._delay);
} else {
super.start();
}
}
/*Setter function for delay attribute*/
public function set delay(seconds:Number){
this._delay = Math.abs(seconds*1000);
}
}

As you can see, I reduced the number of functions, used the simpler setTimeOut and rely more on inheritance and overriding than in the previous version. I also decided to make and AS3 version.

package com.vfd.animation.tweens{
import fl.transitions.Tween;
import flash.utils.setTimeout;
/**
* @author Jeremy Wischusen
* This class allows for a delay before starting the animation.
*/
public class DelayedTween extends Tween {
/*
Holds the number of seconds to wait before starting the animation.
*/
private var _delay:Number = 0;
public function DelayedTween(object, property, easingFunction, start, end, duration, useSeconds, delay) {
this.delay = delay ;
super(object,property,easingFunction,start,end,duration,useSeconds);
}
/*Override the default start function so that the delay can be applied.*/
public override function start():void {
if (this._delay>0) {
setTimeout(super.start,this._delay);
} else {
super.start();
}
}
/*Setter function for delay attribute*/
public function set delay(seconds:Number):void {
this._delay = Math.abs(seconds*1000);
}
}
}

I have noticed that occasionally the compiler spits out:
The superconstructor must be called first in the constructor body.

If you place the super constructor before the delay variable is set, the tween just starts immediately since the variable has a default value of 0. This is what caused the need for the additional functions in the first version. While the compiler may occasionally complain (sometimes it shows the message and other times it does not), it still compiles and works.

Will be committing these to the repository on Google code sometime today.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 2, ActionScript 3, OOP, Open Source Projects Comments No Comments »

12th Aug 2008

Cycling Fading Clips Using Tweens

I did this to answer a post on Flashkit and just to have something to play with. You can see the original post here. The indidividual wanted to have 3 clips fade in and out in sequence and have that sequence rotate. Here is what I came up with:

import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.*;
/*
Create tween objects and immediately stop them so that they can be re-used.
*/
var yellowTween:Tween = new Tween (circle_mc.yellow_mc, “alpha”, None.easeInOut, 0 , 1 , 2 , true );
yellowTween.stop();
var blueTween:Tween = new Tween (circle_mc.blue_mc, “alpha”, None.easeInOut, 0 , 1 , 2 , true );
blueTween.stop();
var redTween:Tween = new Tween (circle_mc.red_mc, “alpha”, None.easeInOut, 0 , 1 , 2 , true);
redTween.stop();
/*Add an event listener to the first tween to trigger the fade in the oposite
direction. Subsequent listeners will be assigned and removed in the event
handler functions.
*/
yellowTween.addEventListener(TweenEvent.MOTION_FINISH, fadeOut);
/*
Since movie clips allow for the creation of dynamic properties (aka variables), simply create a
refence to the next tween that should be triggered directly on the clip. With
this system you could easily add aditional clips by cretaing a new tween and adding
another reference on the new clip to be tweened.
*/
circle_mc.yellow_mc.nextTween = blueTween;
circle_mc.blue_mc.nextTween = redTween;
circle_mc.red_mc.nextTween = yellowTween;
/*
Start the first tween to kick off the sequence. This should be the tween that you
added the event listener to in the previous code.
*/
yellowTween.start();

/*
Create a generic handler for the end of the fade in event. Since the TweenEvent object
holds a reference to the tween that caused the even, we can reference that tween via
the event.target property.
*/
function fadeOut(event:TweenEvent) {
/*remove the event listener that triggers this function from the tween since we have
gotten past the point of needed it and we dont want it to complete with the next part
of the sequence.
*/
event.target.removeEventListener(TweenEvent.MOTION_FINISH, fadeOut);
/*Add a new event listener that will trigger the next part of the sequence*/
event.target.addEventListener(TweenEvent.MOTION_FINISH, startNext);
/*Set the begin and finish properties of the tween object to the oposites
of those we used to create the fade in effect. I had originally tried to do
this with the built in yoyo function, but it produced un expected results.
*/
event.target.begin = 1;
event.target.finish = 0;
/*Restart the tween with the new properties, when this tween is finished,
it will trigger the new event handler we assigned in this function and
continue the sequence.
*/
event.target.start();
}
/*Now that the tween has fadded in and out, start the next tween. Again since TweenEvent
holds a reference to the tween that triggered the event, we can reference that tween.
Additionally, since the tween object holds a reference to the clip being tweened,
we can reference the properties of that clip. In this case we are interested in the
nextTween property we assigned in the previous code as this is what we will use
to start the next tween.
*/
function startNext(event:TweenEvent) {
/*Removed the event listener that triggered this function.*/
event.target.removeEventListener(TweenEvent.MOTION_FINISH, startNext);
/*
event.target is the tween that tirggred the function. obj is the property on
the tween objetc that holds a reference to the clip being tweened. hence, we can
reference the next tween to be triggered by accessing the nextTween property we created.
*/
/*
add a listener to trigger the fade out function completing the logical loop.
*/
event.target.obj.nextTween.addEventListener(TweenEvent.MOTION_FINISH, fadeOut);
/*Reset the values of the tween so that the effect is to fade in.*/
event.target.obj.nextTween.begin = 0;
event.target.obj.nextTween.finish = 1;
/*start the tween and the cycle repeate itself.*/
event.target.obj.nextTween.start();
}

After some playing with it, I was able to get it down to this:

import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.*;
var yellowTween:Tween = new Tween (pics_mc.yellow_mc, “alpha”, None.easeInOut, 0 , 1 , 2 , true );
yellowTween.stop();
yellowTween.addEventListener(TweenEvent.MOTION_FINISH,fadeOut);

if (pics_mc.numChildren > 1) {
for (var c:int = pics_mc.numChildren-1; c>=0; c–) {
var clip:Object = pics_mc.getChildAt(c);
clip.alpha = 0;
if (c > 0) {
clip.nextClip = pics_mc.getChildAt(c-1);
} else {
clip.nextClip = pics_mc.getChildAt(pics_mc.numChildren-1);
}
trace (pics_mc.getChildAt(c).name)
trace (clip.nextClip.name)
}
}

yellowTween.start();

function fadeOut(event:TweenEvent) {
event.target.removeEventListener(TweenEvent.MOTION_FINISH, fadeOut);
event.target.addEventListener(TweenEvent.MOTION_FINISH, startNext);
event.target.begin = 1;
event.target.finish = 0;
event.target.start();
}
function startNext(event:TweenEvent) {
event.target.removeEventListener(TweenEvent.MOTION_FINISH, startNext);
event.target.addEventListener(TweenEvent.MOTION_FINISH, fadeOut);
event.target.obj = event.target.obj.nextClip;
event.target.begin = 0;
event.target.finish = 1;
event.target.start();
}

As long as all of the transitions are to be of the same length this works fine and all you would have to do to continue this would be to add additional clips to the housing clip (pics_mc) and the transition would be applied for you.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3 Comments No Comments »

08th Aug 2008

An Eventful Revision

I finally got some time to play with my AnimatedClip class. I had a few ideas I wanted to try out. While playing with it, I realized that there was no real way to respond to tween events as all of the tweens resided in private instance variables. So I went back and added getter methods for the tween that I though people might like to respond to. So now you can do something like this:

//ball has com.vfd.animation.AnimatedClip linked to it via the library linkage.

import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
ball.easing= Bounce.easeInOut;
ball.sizeTo(300,300,5);
ball.widthTween.addEventListener(TweenEvent.MOTION_FINISH, motionFinished);
function motionFinished(evt:TweenEvent) {
ball.widthTween.yoyo();
ball.heightTween.yoyo();
}

Will add this into the repository when I get home. I am mostly working on the AS3 version at this point.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, Open Source Projects Comments No Comments »

08th Aug 2008

Enforcing a Singleton

Been doing some research on Cairngorm and in the process came across this little trick for enforcing singletons. ActionScript will not let you set the access modifier for a constructor to private and as such, despite having a singelton architecture, there would be nothing stopping someone from directly calling new Singleton, which defeat the purpose of a singleton in the first place. The solution involves using what amounts to a private class that is a required argument of the constructor. This looks like this:

package
{

/**
* …
* @author Jeremy Wischusen <cortex@visualflowdesigns.com>
*/
public class Singleton
{
private static var instance:Singleton;
public function Singleton(enforcer:SingletonEnforcer)
{

}
public static function getInstance():Singleton
{
if (Singleton.instance == null)
{
Singleton.instance = new Singleton(new SingletonEnforcer);
}
return Singleton.instance;

}
}

}
class SingletonEnforcer
{}

Notice the class definition for SingletonEnforcer is ourside of the package definition. When you define a class like this in the same file as a another class, it is only available to main class defined in the file (the one inside the package statement).  In other words the class is private. Since the constructor requires an instance of this class, trying to instantiate using new Singleton will throw an error since there is no way that an enforcer can be created and passed to the constructor other than within the Singleton class itself.

Hopefully in future versions of ActionScript we will have private constructors (along with method overloading just in case anyone is listening hint hint), but for now, this should do the trick.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, OOP Comments No Comments »

26th May 2008

Hey Look, a Mouse.

In one of the books I am reading, Foundation Actionscript 3.0 Animation : Making Things Move! by Keith Peters, he has an example of using trig to make an arrow point at the location of the mouse. I decided to play with this a bit and make an animation where the eyes follow the mouse. I actully ended up adding this to my animation class, so this (after attaching the class via the library linkage):

can be accomplished with:

leftEye.startWatchingMouse();
rightEye.startWatchingMouse();

Functions in class:

public function startWatchingMouse():void{
stage.addEventListener(MouseEvent.MOUSE_MOVE,watchMouse);
}
public function stopWatchingMouse():void{
stage.removeEventListener(MouseEvent.MOUSE_MOVE,watchMouse);
}
private function watchMouse(event:MouseEvent):void{
var dx:Number = stage.mouseX - this.x;
var dy:Number = stage.mouseY - this.y;
var rad:Number = Math.atan2(dy,dx);
//for some reason the example as written was 90 degrees off, so I added 90 and that fixed it.
this.rotation = rad*180/Math.PI + 90;
}

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, OOP Comments No Comments »

25th May 2008

Flex YouTube Video Search

Since I had such a fun time with the Truveo video search, I decided to do the same type of thing with YouTube. I was originally going to have it play the video, but as it turns out for some reason when loading a YouTube player into a SWFLoader, it only works the first time and the fixes I found are a little more than I can to put into something that is basically just an experiment.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, Flex Comments No Comments »

21st May 2008

Flex Truveo Video Search

A few weeks ago someone contacted me about writing about the new APIs that AOL has made available. While looking at the AOL dev site I came accross the Truveo API and decided I would try creating a search application in Flex.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, Flex Comments No Comments »

14th May 2008

AS 3 Animated Clip Class

So recently I finished (as in have something usable, they’re never finished) an AS3 animation class.

Basically I client of mine had me use mc_tween.as for a few projects and I decide to have a go at creating something similar in AS3 (from what I have read on the author’s site, he to is working on an AS3 version).

If you want to check out the class, you can find it on google code. Again, all of this stuff is a work in progress, so bugs are par for the course.

Here is a quick sample of how it can be used. The following example is created using this code:

//ball is a movie clip whose class I have set in the linkage dialog to com.vfd.animation.AnimatedClip;
import fl.transitions.easing.*
ball.easing = Bounce.easeInOut
ball.fadeTo(0,2, true);
ball.sizeTo(10,10, 2, true);
ball.spinTo(90, 2, true)
ball.orbitDistance = 50;
ball.startOrbit();

UPDATE:

Also started an AS 2 version. In the same code repository on google code.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, OOP, Open Source Projects Comments No Comments »

29th Apr 2008

Setting the Initial Sort for a Flex DataGrid Component

A client asked me recently to to have the data being displayed in a Data Grid be initially sorted by store name (See Creating an Image Reflection in Flex to view the project in question). The way you do this is by sorting the Datagrid’s data provider. To do this, you need to create a sort object, assign it some sort fields, set that sort object as the dataprovider’s sort object (so you have to be using some sort of sortable collection to do it this way) and refresh the collection. This looks something like this:

private var storesXMLCollection:XMLListCollection = new XMLListCollection();
private var initSort:Sort = new Sort();

/ /SortField(name:String = null, caseInsensitive:Boolean = false, descending:Boolean = false, numeric:Boolean = false) so in this case companyName is the XML Node I am sorting on and the second parameter indicates that the sort should be case insensitive.

this.initSort.fields = [new SortField("companyName", true)];

this.storesXMLCollection.sort = this.initSort;

//once the sort object has been applied, refresh the collection.

this.storesXMLCollection.refresh();

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, Flex Comments No Comments »