kreativeKING - Interactive Developer

Posts tagged “AS3”

Where’s my Sound ???

Here’s a Handy little tip I just figured out today. So I have a button that plays sound and once if finishes playing it should fire the Event.SOUND_COMPLETE. In this events handler, it resets the position back to the beginning of the clip. Now the problem is once I try to play it again, it doesn’t seem to fire the Event.SOUND_COMPLETE event. Have you ever had the issue of your Event.SOUND_COMPLETE not firing properly?? Read on and find out why……

After some debugging, I noticed that every time you pause a sound and play it again, a new SoundChannel is returned. Any event listeners I had applied to the SoundChannel before are disregarded once I pause and play. Instead of :


function playSound():void
{
mySound : Sound = new Sound();
mySound.addEventListener(Event.COMPLETE, soundLoaded);
mySound.load(MY SONG REQUEST);
}

function soundLoaded(e : Event):void
{
myChannel = new SoundChannel();
myChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);
myChannel = mySound.play();
}

function soundComplete(e : Event):void
{
position = 0;
playChannel()
pauseChannel();
myChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);
}

function pauseChannel():void
{
myChannel.stop();
position = myChannel.position;
}

function playChannel():void
{
myChannel = mySound.play(position);
}

But It should be :


function playSound():void
{
mySound : Sound = new Sound();
mySound.addEventListener(Event.COMPLETE, soundLoaded);
mySound.load(MY SONG REQUEST);
}

function soundLoaded(e : Event):void
{
myChannel = new SoundChannel();
myChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);
myChannel = mySound.play();
}

function soundComplete(e : Event):void
{
position = 0;
playChannel();
pauseChannel();
}

function pauseChannel():void
{
myChannel.stop();
position = myChannel.position;
}

function playChannel():void
{
myChannel = mySound.play(position);
myChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);
}

You need to register the event listener again once you call play. I hope this saves 30 minutes of your day once you start screaming…WHERE’S MY SOUND!!!

Cool Flash Tip of the Week 5

Hey Flashers, I know its been a long time since the last tip. Time has not been on my side recently, but I’m getting some more free time and I’ll be posting regularly again. Be on the look out, I have some new websites and articles coming out. You can see the latest website to date, Galley Smith Blog. But aside from all of that, down to the tip.



I’m currently working on a 3D Flash site and I decided to use Flash 10 3D instead of Papervision3D. I felt it would be overkill to use Papervision for this project since we couldn’t get our animated 3d models into Papervision successfully. As everyone knows or some who don’t, FP10 ‘s z sorting is non-existent. I needed to have floating panels zoom up to show maximized version of the panel. The problem is that, scaling them up, if it is not at the top of the DisplayList, it would show the other panels in front of it still.



I needed to make a function that would always keep my selected panel above the rest. The kreativeSort function was born. Its still in its infancy, but I see potential in it. I will work on it more throughout the project at keep everyone up to date with the progress. Here is the commented function for everyone to use if you happen to have the same issue.




Update



I’ve been steered in a better direction and found of an alternative and faster way of doing this over at Actionscript.org from lordofduct. Check out the updated function at the bottom.






Without KreativeSort





With KreativeSort






/**
* Puts selected DisplayObject on top of other DisplayObects in its container
*
* @param parent Container DisplayObject that holds our children.
* @param panel Child we want to be displayed on top of the rest
*
* @author Clemente Gomez - kreativeKING
*/
private function kreativeSort(parent:DisplayObjectContainer, panel:DisplayObject) : void
{
var i : int = 0;
var length : Number = parent.numChildren;

//Position the child is located at.
var pos:int;

for (i ; i < length ; i++)
{
// When child matches the level we are at in the container, recored the level in variable "pos".
if(parent.getChildAt(i) == panel)
{
pos = i;
break;
}
}
// Removes child out of container.
parent.removeChildAt(pos);

//Adds the child back on top of the rest.
parent.addChildAt(panel, parent.numChildren);

}







Updated Function

function kreativeSort( parent:DisplayObjectContainer, panel:DisplayObject ):void
{
if (parent.contains( panel )) parent.addChild( panel );
}

Web Designer Magazine 159

Hey people, I’ve been published again in Web Designer Magazine Issue 159. In this tutorial, I walk you through how to make a MP3 player with a sound visualizer. Its a pretty short and straight to the point tutorial. Hopefully everyone will be able to follow along and make some cool mp3 players. If there are any concerns or questions, post it here on the blog and I’ll get back to you ASAP.




Go pick up your copy and leave some feed back. Check out a preview here

Cool Flash Tip of the Week 3

Welcome back everyone for the 3rd installment of the Cool Flash Tip of the Week Series. This week we are going to take a look at a new class introduced with Flash Player 10. Say hello to the Vector Class.





The Vector class is very similar to the Array class which we all know and love. The difference is that a Vector only holds one data type. An Array can holds several different kinds of values. A Vector is an Array of the same type. Check out the psuedo code underneath to get a better understanding of what I mean.





//Array
[ String, Number, ,int, Sprite ];

//Vector
[ String, String, null, String, String ];




If you paid close attention to that last snippet, you notice that the Array has an empty index, which is just fine. But when it comes to a Vector, there can not be any empty indices. If you must have an empty spot, make sure to set the value to null. Leaving it empty will throw an Error. A Vector is a dense data typed Array. Moving right along, to create a Vector is quite different than creating any other instance in Actionscript 3. Check out the example below.





//Syntax
Vector.

//Correct
var myVector:Vector. = new Vector.();

//Throws Error
var myVector:Vector. = new Vector.();




As you can see, the type of the Vector can only be instantiated to that class. Even though Sprite is a subclass of DisplayObject. So make sure to avoid this and you should have a smooth time. There is however a way we can still make this work. This would be using the Vector() function. This will allow you to turn an Array or Vector into another base class.





//Copy a Sprite Vector to a DisplayObject Vector
var myVector:Vector. = new Vector.();
myVector[0] = new Sprite();
var myVector2:Vector. = Vector.(myVector);

//Copy an Array to a Vector
var myArray:Array = [new Sprite(), new Sprite()];
var myVector2:Vector. = Vector.(myArray);

//Make sure your Array are all the same Type or you will get an Error
var myArray:Array = [new Sprite(), new Sprite(), new String()];
var myVector2:Vector. = Vector.(myArray); //Throws Error because String is not a DisplayObject

//They can all be DisplayObjects though
var myArray:Array = [new Sprite(), new Sprite(), new MovieClip()];
var myVector2:Vector. = Vector.(myArray); // Accepts this array since Sprite and MovieClips are both DisplayObjects




So based on our examples, directly assigning a SubClass Vector to a SuperClass Vector will throw an Error. You must copy the Array or Vector into the the Super Class Vector. The Vector constructor takes 2 optional parameters. The first parameter is the length and the second is the fixed parameter. If you set the fixed parameter to true, trying to create something in an index past that will throw an Error. This result is the same when using a method that changes the length of the Vector such as pop(), push(), etc.






var myVector2:Vector. = new Vector.(3, true);
trace(myVector2) //outputs null,null,null

var myVector2:Vector. = new Vector.(3, true);
myVector2[3] = new Sprite(); // Throws Error because fixed is set to true and we tried to place something in an index that exceeds the length.




Now with all these restrictions, this makes Vector a lot faster than using Arrays and is recommended when dealing with an Array which holds all the same DataType. Vectors are approximately 40% faster according to Mike Chambers to Arrays. When dealing with a large Array that is the same type, use a Vector. Also note that Vectors are only available in Flash Player 10, so that is bit of a downfall for the moment, but will be the new standard once the Flash Player 10 penetration numbers get higher.




Hopefully this little look into Vectors will get you to make the switch if you are publishing to the 10th version of the Flash Player. Next week, be prepared, we Are going to take a look into a Custom Class. If you enjoyed this post, tweet it, share it, bookmark it and subscribe. Stay tuned for next week.




More Info

Cool Flash Tip of the Week 2

I’ve gotten a lot of positive feedback on the Cool Flash Tip of the Week series. So as long as people find them useful, I’ll keep them coming. Make sure to subscribe to be on top of all tips and add me on twitter. Now with all the formalities out the way, lets get a move on to the tip of the week. This week’s tip is about Events!!





I’m sure you are wondering, what kind of tips can you not know already. Events are a big topic in Actionscript 3.0. Almost everything is based on event listeners and is event driven. During my time coding, I found a couple of handy shortcuts that made my day easier. Let’s say you have a  simple event handler that adds a MovieClip to the stage when a link is clicked. For simplicity’s sake , lets pretend we have a MovieClip in the library named “myMC”, and a button on the stage called “myLink”.






myLink.addEventListener(MouseEvent.CLICK, addClip);

function addClip(e:MouseEvent):void
{
stage.addChild(myClip);
}



This would be the typical way we would do it. This is absolutely correct, but what if we wanted in a different function to add the clip as well. Some one would probably try to execute that this way.





myLink.addEventListener(MouseEvent.CLICK, addClip);
otherFunction();

function addClip(e:MouseEvent):void
{
stage.addChild(myClip);
}

function otherFunction():void
{
stage.addChild(myClip);
}



Although this is correct, the ideal way to program is to reuse code as much as possible so that when its time to update you caan change the code in one spot and it will update throughout the program. Not to mention it cleans up the code considerably. A better alternative to this would be to call addClip(). But WAIT!!, this is an event handler, if I call this I get an Argument Error. This is true, but we can setup the event handler to be an event listener and also be called without needing an event. Here is how we acheive that.





myLink.addEventListener(MouseEvent.CLICK, addClip);
addClip();

function addClip(e:MouseEvent = null):void
{
stage.addChild(myClip);
}

//------------------OR--------------------
myLink.addEventListener(MouseEvent.CLICK, addClip);
addClip(null);

function addClip(e:MouseEvent):void
{
stage.addChild(myClip);
}



That was pretty simple now was it. I use this all the time in my code to shorten things up and clean my code. I do prefer to the first method than the second alternative. I rather not have to keep passing null than just setting the default to null instead. Keep in mind, that this will only work if you do not need the actual event in your functions logic. If you do, then you need to an event. Well that’s all for this week’s tip. I hope you found it useful in any sense. Next week will be a big week, so stay tuned and subscribe to the feed.

Cool Flash Tip of the Week 1

I’m going to start a series that will occur every week. A cool flash tip or something I think not many people know about. Be on the lookout every week for a new tip. This week’s CFT is ……drumroll…….” The Tertiary Operator “.








I spend alot of time traversing flash posts looking at other peoples code and I often see a large if else block to change a simple variable. Using the Tertiary Operator we can simplify this into one line of code. Shorter code is always better in my opinion. Plus can save you a couple bytes in your code.



Here is an example of what I see.















var myBool:Boolean = false;
var myVar:Number = 12;

if(myBool == true)
{
myVar = 15;
}
else if(myBool == false && myVar == 10)
{
myVar = 40;
}
else
{
myVar = 0;
}



Now this is all well and dandy, but it is a waste of space and can be simplified by a lot. One, when testing a Boolean there is no need to test to true or false. Instead if you want to test if something is true, you can just place the variable in the if parenthesis. This will automatically test to true. To test if a variable is false, use !. Here is an example.






var myBool:Boolean = false;
var myVar:Number = 12;

if(myBool )
{
myVar = 15;
}
else if(!myBool && myVar == 10)
{
myVar = 40;
}
else
{
myVar = 0;
}



This already shortens up our code a bit. But we can take this a step further using the Tertiary Operator. The syntax for this is pretty simple once you know what it means.






//Tertiary Syntax

(Test) ? True : False;






Basically, If the test is true, the code after the ? executes. If the test is false the code after the : executes.








  • ? = if

  • : = else







You can also string together Tertiary statements to make and if else if else etc. Here’s how we write the same code from above over using the Tertiary Operator.






var myBool:Boolean = false;
var myVar:Number = 12;

myVar = (myBool ) ? 15 : (!myBool && myVar == 10) ? 40 : 0;






WOW, look how much space we saved, and it i still readable. I implore everyone to start using this and save space =D. Be aware that it is advised no to string Tertiary statements past “If..Else”. If you liked this idea of CFT ( Cool Flash Tip ), then leave a comment, subscribe to the feed or / and follow me on twitter. It would be great to get some feedback on if this is helpful or not and maybe some tips you would like to see featured here.






Happy Flashing

AS3 Basic Preloader Class



  • Languages

    - Actionscript 3.0



  • Purpose

    - A basic calls to build preloaders from. It is meant to act as a starting point to build more advanced preloaders. It is available for free download


  • Download Here

XMLLoader 3.0 Update

Fixed a small bug that was confusing the names and actual data. Link in the last post has been updated to the bug fixed version. This is just a courtesy posy to the ones who have already downloaded the class to download it again. Enjoy and keep me updated on bugs you may find or features you would like in the future.

I’m always available @cg219.


Download Link

New XMLLoader 3.0 Release

I have finally gotten around to updating the XMLLoader Class now, in its 3rd Release. With this release comes a couple new properties such as bytesLoaded, bytesTotal, totalItems, currentItem and ratioLoaded. The biggest update is the new naming feature. With this feature you can now give each XML file a name to reference it. Also in the big boat of updates is the new way of handling errors.


The new naming feature is meant to replace the old naming feature in version 2.0. TO refresh everyone’s memories, the older version would automatically name the file for you by using the actual name of the file. If there happened to be more than one file that had the same name, it would attach a number depending on its spot in the Array. I’ve come to realize, this way was really unproductive and annoying. So to combat that, I created a new naming feature. This naming feature allows you to call each XML file anything you you want.

In order to use this new feature, you must pass in another Array which contains the names in the order that the XML files are being loaded in. For Example:




package
{
import com.clementegomez.utils.XMLLoader;
import flash.display.*;
import flash.events.*;

public class XMLDoc extends MovieClip
{
public var xl:XMLLoader;
public var array:Array;
public function XMLDoc()
{
xl = new XMLLoader();
array = new Array();
xl.addEventListener(Event.COMPLETE, loaded);

xl.loadXML(["http://flashden.net/feeds/user_item_comments/cg219.atom", "http://feeds2.feedburner.com/kreativeking?format=xml"], ["xml1", "xml2"]);
}

private function loaded(e:Event):void
{
trace(xl.data["xml1"]);
}
}
}


In the previous example, we pass in a second array of strings to the loadXML() function. the first string “xml1” will be the name of the first XML file in the array and “xml2” refers to the second. With this, you can reference the XML file by name later on in code rather than its index number.

The new properties include ratioLoaded which returns the amount of items loaded to the total amount of items as a Number between 0 and 1. The currentItem property returns the number of the current XML being loaded and the totalItems property returns the total amount of XML files. The bytesLoaded and bytesTotal return those properties of the current XML file being loaded.

The new Error handling has been improved as well. A new property has been added called skipErrors. This is set to true by default. When this property is set to true, if there happens to be an error in the Array of XML files such as a dead link or misspelled url, it will be skipped and the loading process will continue. This is set to true by default, so if you would like to receive the Error messages, set this property to false.

Official Documentation can be found here
Download the Class files here

AS3 Basic Preloader Class

I been thinking of ways to preload things in AS3 like you would in AS2. Meaning a simple drag and drop and it preloads. I unfortunately couldn’t come to a solution of just drag and drop. But I have gotten pretty damn close. Last night I started working on a Basic Preloader Class in which I can build more complex preloaders off of. Just like some of the classes in my VIdeoPlayer API, the Base Class gets replaced with BasicPreloader to give it its functionality.


All the BasicPreloader does is load the content, whether is be a Loader or URLLoader operation, show the progress and a complete function. In addition I added a render function which I will build more upon in an Extended class to show some sort of animation. Here is the syntax:




BasicLoader.load(urlString, loaderOrURLLoader);




The Load function takes two parameters. First it takes a string path of the file you want to load. Secondly it takes a string to represent if you are want to use a URLLoader procedure or Loader procedure. To pass the second parameter, it’s best to use the constants packaged with Class which are BasicPreloader.URLLOADER and BasicPreloader.LOADER.

That is the only public function in the class. The other functions protected and can be accessed through class extensions. I hope this will help people out in the community. If you know of any other features that should be added to the Base Class, don’t hesitate to drop me a line or end me a tweet.




Download Here

Here is the Class:

/**
* @author Clemente Gomez.
* @email zomegpro@gmail.com.
* @link http://blog.kreativeking.com.
* @build 1.0 (03-23-09)
* @description Base class to preload assets
*
* @public constants:
* LOADER:String;
* URLLOADER:String;
*
* @public properies:
* bytesLoaded:Number;
* bytesTotal:Number;
* precentage:Number;
* roundedPercentage;
*
* @public methods:
* BasicPreloader() - Constructor.
* load($url:String, $type:String = LOADER):void
*
*/
package com.clementegomez.utils.preloaders
{
import com.clementegomez.events.ParamEvent;
import com.clementegomez.utils.LoaderHelper;

import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;

public class BasicPreloader extends Sprite
{
public static const LOADER:String = "loader";
public static const URLLOADER:String = "urlLoader";

private var url:URLRequest;
private var loader:Loader;
private var urlLoader:URLLoader;
private var loadedBytes:Number;
private var totalBytes:Number;
private var percent:Number;
private var loaderHelper:LoaderHelper;

/**
* The BasicPreloader class is the Base for preloaders. It has all the basic function of
* a preloader. This can be either attached to MovieClip in the library or created dynamically in
* Actionscript 3.0. When attached to a MovieClip you can call the loader at anytime to load your content. This
* class by itself isn’t much visually, this class is mainly to be build upon to create more powerful
* preloaders.
*
* @return = null;
*/
public function BasicPreloader()
{
init();
}

private function init():void
{
trace(“Basic Preloader Initialized”);
}

/**
* THe load function starts the loading process of the asset. The load function accepts two parameters. The
* first being a String to the asset being loaded and the second being a string to describe
* the type of load procedure to use;
*
* @param $url String path to the asset to be loaded.
* @param $type BasicPreloader.LOADER to use the Loader procedure or
* BasicPreloader.URLLOADER to use the URLLoader procedure.
* @default BasicPreloader.LOADER
*
* @return null
* @example Here is an example of the loade function.
*
*
* BasicPreloader.load(“examplePic1.jpg”, BasicPreloader.LOADER);
*
*
*
*/
public function load($url:String, $type:String = LOADER):void
{
if($type == LOADER)
{
loader = new Loader();
loaderHelper = new LoaderHelper(loader, $type);
loaderHelper.addEventListener(ParamEvent.PARAM, complete);
loaderHelper.addEventListener(ParamEvent.PERCENT, showProgress);
loader.load(new URLRequest($url));
}
else if($type == URLLOADER)
{
urlLoader = new URLLoader();
loaderHelper = new LoaderHelper(urlLoader, $type);
loaderHelper.addEventListener(ParamEvent.PARAM, complete);
loaderHelper.addEventListener(ParamEvent.PERCENT, showProgress);
urlLoader.load(new URLRequest($url));
}
else
{
throw new Error(“Type must be of class Loader or URLLoader”);
}
}

protected function showProgress(e:ParamEvent = null):void
{
loadedBytes = ((e.target as LoaderHelper).progress as ProgressEvent).bytesLoaded;
totalBytes = ((e.target as LoaderHelper).progress as ProgressEvent).bytesTotal;
percent = (loadedBytes / totalBytes) * 100;
dispatchEvent(((e.target as LoaderHelper).progress as ProgressEvent).clone());
render();
}

protected function render():void
{
trace(“animation : ” + percent);
}

protected function complete(e:ParamEvent = null):void
{
loaderHelper.removeEventListener(ParamEvent.PARAM, complete);
loaderHelper.removeEventListener(ParamEvent.PERCENT, showProgress);
dispatchEvent(((e.target as LoaderHelper).event as Event).clone());
}

/**
* Return the amount of loaded bytes.
* @return Number
*/
public function get bytesLoaded():Number
{
return loadedBytes;
}

/**
* Return the amount of total bytes.
* @return Number
*/
public function get bytesTotal():Number
{
return totalBytes;
}

/**
* Return the percentage of loaded bytes.
* @return Number
*/
public function get percentage():Number
{
return percent;
}

/**
* Return the percentage rounded to the nearest interger of loaded bytes.
* @return Number
*/
public function get roundedPercentage():Number
{
return Math.round(percent);
}
}
}

More Information