Category: Flash

world.CreateBody() creating NULL ??

I was doing some test stuff for a game that uses Box 2D flash. I found and learned a thing that i didn’t knew and it was very important. I had created a world with some bodies(polygons and circles) added to it. I was destroying and creating bodies just to play around. So when i was creating a body dynamically at runtime, i found out that body wasn’t getting created because world.CreateBody(bodyDef) was returning NULL. I was really surprised when i found this. I traced everything like if bodyDef and world was not null and all that. So i was looking through my code again and again to find why world.CreateBody was returning null. Then i was suspicious about something. So what i did something to confirm my suspicion that before creating a body i waited all body to sleep i.e when they are not moving or interacting. After all bodies were sleep i created a body and viola bingo bang boom my body was created. So my suspicion was true that when world is stepping then world.CreateBody always returned null (I tested it again and again). Hmnnnnnn so this was pretty interesting. I am still working around to find a solution for this as i haven’t find any very graceful good solution to create a body during world step. if you have any suggestion/tips or solution please do share.


Today i was doing some experiment with google translate API. I was trying to use google translate API with AS3. I found many snippets while googling that was using flex but i wanted to do it in flash as3. So I wrote a very basic code snippet to translate text from one language to other using google translate API.

Well i have created two combobox on my fla. I have given instance name to them and then i am just taking the language input for translating text from one language to other.

The main crucial part:


I am just making a GET HTTP Call to google translate API passing input, and language pair (i.e en(english) to es(espanol) etc). It returns result in JSON. On my flash client i decode that JSON and display the translated result.
Note: escape method is used to encode the string to url encoded format

Here is the source code:

	import com.adobe.serialization.json.JSON;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import fl.data.DataProvider; 
	 * ...
	 * @author padam
	public class Main extends Sprite 
		public function Main():void 
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		private function init(e:Event = null):void 
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			button_p.addEventListener(MouseEvent.CLICK, translate);
		private function initGUI():void {
			var itemsFrom:Array = [ 
			{label:"English", data:"en"}, 
			{label:"Spanish", data:"es"}, 
			{label:"French", data:"fr"}, 
			{label:"Italian", data:"it"}
			var itemsTo:Array = [
			{label:"Hindi", data:"hi"},
			{label:"English", data:"en"}, 
			{label:"Spanish", data:"es"}, 
			{label:"French", data:"fr"}, 
			{label:"Italian", data:"it" }
			fromLanguageCombo.prompt = "Select Language"; 
			fromLanguageCombo.dataProvider = new DataProvider(itemsFrom);
			toLanguageCombo.dataProvider = new DataProvider(itemsTo);
		private function translate(event:MouseEvent):void {
			var request:URLRequest=new URLRequest();
			request.method = URLRequestMethod.GET;
			var loader:URLLoader=new URLLoader();
			catch (error:Error) 
		private function messageSent(evt:Event):void
			var loader:URLLoader=URLLoader(evt.target);
			var result:String = loader.data as String;
			var json_1:Object = JSON.decode(result);
			output.text = json_1["responseData"]["translatedText"];
			translationLabel.text = fromLanguageCombo.selectedItem.label + " to " + toLanguageCombo.selectedItem.label+" translation";

Well there is nothing much in code. Just taking the language values from two combo box list and passing it to the translate api. Then after decoding json that i received from api call, i am displaying on textfield. Anyway please note that translate api has been officialy depracated.

Here is the quote from API site:

Important: The Google Translate API has been officially deprecated as of May 26, 2011. Due to the substantial economic burden caused by extensive abuse, the number of requests you may make per day will be limited and the API will be shut off completely on December 1, 2011. For website translations, we encourage you to use the Google Translate Element.


I am making a very small 3d game (isometric view) using papervision3d. I needed some dynamic shadow element for some elements. I came across this very wonderful class that does the shadow casting from here. So I used ShadowCaster class to cast my shadows of my displayobject3d. I would need this following things for my purpose:
1) A do3d, target object whose shadow has to be created/rendered
2) A light source
3) A plane at which shadow would fall/render.
4) And of course our ShadowCaster class 😀

So i started playing with the shadowcaster class to get my hands dirty. I was trying to cast shadows of 4 plane on another surface plane. I created a light source. So here is how i was casting shadow with the code:

var blurr:BlurFilter = new BlurFilter(10, 10, 1);

shadowCaster_one = new ShadowCaster("plane1_shadow", 0x000000, BlendMode.MULTIPLY, 0.3, [blurr]);

shadowCaster_two = new ShadowCaster("plane2_shadow", 0x000000, BlendMode.MULTIPLY, 1, [blurr]);

shadowCaster_three = new ShadowCaster("plane3_shadow", 0x000000, BlendMode.MULTIPLY, 0.3, [blurr]);

shadowCaster_four = new ShadowCaster("plane4_shadow", 0x000000, BlendMode.MULTIPLY, 1, [blurr]);

Above I created 4 separate shadowcaster to cast on 4 separate plane.

override protected function onRenderTick(event:Event = null):void


shadowCaster_one.castModel(plane1, light, shadowPlane);
shadowCaster_two.castModel(plane2, light, shadowPlane);
shadowCaster_three.castModel(plane3, light, shadowPlane);
shadowCaster_four.castModel(plane4, light, shadowPlane);

Above I am rendering four shadows of four separate planes. I am rendering them on onRenderTick. Now its time to test it in browser.
1) Google chrome browser: Smooth run
2) Firefox: smooth run
3) Safari: smooth run
4) Opera: smooth run
5) Internet Explorer: FPS:1~0 (very very very very lag)

Yes there was very massive frame rate drop on internet explorer, interactive response was almost none. All other browser ran the game smoothly. Only one thing came to my mind:” Internet Explorer sucks”, but i knew that i had to optimize my code and for that i had to find the code that was consuming so much memory resource. My first suspect was shadow casting code at onRenderTick(), so i commented all shadow casting line and ran it again in internet explorer and yeah you guessed it correct that it ran smoothly. But i had to cast the shadows so i need to optimize this part. So i did some alteration:

First instead of adding those 4 planes directly to scene, i added them to one do3d.


Second, instead of creating 4 shadow caster, i created only one caster that would cast onto displayobject3d which has four planes as its children.
shadowCaster = new ShadowCaster("plane4_shadow", 0x000000, BlendMode.MULTIPLY, 1, [blurr]);


Then cast and render the shadow:

shadowCaster.castModel(shadowObjectContainer, light, shadowPlane);

This really optimized the performance and frame rate on internet explorer went up.

I am not claiming that this is the way to write. I am just sharing what i just faced and how i tackled it. I am still working on more better approach for optimization of my code and objective. But still i would say internet explorer sucks as only this browser showed massive drop on fps rate without any optimized code :D. But yeah i know writing efficient code makes life easier 😛


Adobe Flash on Android ?

I have seen demos showing flash sites opening on high end android devices like HTC Desire HD or Nexus One. So i was looking through the posts about installing adobe flash player 10.1 on my lg optimus one p500 (android 2.2). The author of that particular blog explained a few steps to install flash 10.1 on android 2.2 phones (specifically mentioning my p500),

1) First The author provided a link to adobe flash player 10.1 as it is not available in android market right now(flash player 10.3 is available). So I downloaded it and installed it on my lg optimus p500. It got installed without having any trouble.
2) I restarted my android phone.
3) I opened my android browser and opened a flash web site.

And guess what?????? yay it worked………….not…………no it didn’t worked :P.
Browser just closed in between loading site. I tried with all browsers on my phone viz Opera, Skyfire, Dolphin HD, same result on all browser. All browser crashed.

So i guess flash player is not supported on my device. But i don’t care hehe 😛


DestroyBody de BOX2D Flash

Destroying box2d(Box2D Flash) objects is always not smooth, if you don’t manage the references properly. Well sometimes it doesn’t get destroyed also even after calling DestroyBody() method because there is still some reference to box2d objects that is active and u have to keep track of that. I had this problem more often. But yeah i again came up with my just stupid solution to tackle above problem and it works. I have tested this in my all Box2D Flash projects.

What i generally do is create a custom class which would represent particular box2d body, for example in pool game i would create a class called Ball. So now i would create a method called getDestructionStatus() which tells me if particular body is eligible for destruction. And second method i would define called destroy(), in destroy() method you can write your cleanup() implementation like if u have some movieclip associated then you can remove it from stage [Note: I didn’t call DestroyBody in destroy() because it didn’t work for me] Something like this :

public function destroy():void {
	//your custom cleanup code before making box2d body eligible for destruction
	destructionStatus = true;	//eligible for destruction	
public function getDestructionStatus():Boolean {
	return destructionStatus;

Now how would u implement ? Well lets say if my ball collides with wall then i want to destroy the ball, so code would look like this:

override public function BeginContact(contact:b2Contact):void 
	if ((contact.GetFixtureA().GetBody().GetUserData() is Wall && contact.GetFixtureB().GetBody().GetUserData() is Ball)) {

Above i am using a custom class that extends b2ContactListener class and i am overriding BeginContact to determine the collision and provide my some custom implementation response. Here is a insight on b2ContactListener tutorial from Allan Bishop.

Now when my ball collides with wall then i call destroy method on it, which runs my custom cleanup and set the destructionState to true. Now i will check for this destructionState and call DestroyMethod, calling DestroyBody in correct context and block matters because as i said if some reference is still pointing to body then it won’t get detroyed. Here is the implementation code:

for (var worldBody:b2Body = world.GetBodyList(); worldBody; worldBody = worldBody.GetNext()) {
	if (worldBody.GetUserData() != null) {
                if (worldBody.GetUserData().getDestructionStatus()) {

                //write a code to update the position, rotation whatever you want of bodies

Now comes the main part:
I want to explicitly point out that i have put DestroyBody call inside the world body list iteration because it always worked for me without any issues, my bodies got destroyed and that was what i wanted. I hope it works for you also. I also want to try other techniques, so if you apply other way to destroy objects then please share with us. It would help me and others a lot xD


LoaderMax befriends Firefox

For my portfolio flash site i am using LoaderMax from greensock. Why did i use LoaderMax ? Well first i just started using LoaderMax and i am new to it. I am using LoaderMax for two very basic reason:
1) Loading multiple images easily. Well i want to calculate whole progress of multiple assets loading and show it in loading progress which was difficult for me to do when doing it in traditional sequential manner (using loader class). It was tough to find bytes total of all images as i used to load images one by one in sequence.
2) Garbage collection/resource release: When i used to load images using typical loader class, i used to face a problem though i later solved it but still i don’t have to go extra step in case of LoaderMax. The problem was when loading was in progress and i closed my browser window then an error was thrown saying “loading never complete” as shown in my previous post. But with LoaderMax i don’t have to worry about it because it releases the memory if loading process gets paused or aborted.

But in this post i am not discussing the tutorial to use LoaderMax or its features. As always i faced a certain problem and i solved it xD. So i wrote a code module including LoaderMax which ran flawlessly on all web browsers (internet explorer, chrome, opera, and safari) but it didn’t run on Mozilla Firefox. When running on Firefox an exception error was getting thrown and i spent 1 hour to find the reason and couldn’t find it and got me pissed me off xD. First let me show you the code module that i wrote and was throwing exception on firefox:

var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});

queue.append( new ImageLoader("img/photo1.jpg", {name:"photo1"}) );
//start loading
function completeHandler(event:LoaderEvent):void {
    var image:ContentDisplay = LoaderMax.getContent("photo1");

here is the screenshot of error:

In first statement of function completeHandler i am retrieving loaded image. I am sending it to my resize algorithm later to resize the original image to fit into my target area. But it throws error on firefox because it says invalid bitmapdata. My resize algorithm takes displayobject as parameter and ContentDisplay extends Sprite class. Note: LoaderMax can also resize your original image according to aspect ratio

I didn't understand why this error was coming in firefox but not in other browsers. At first i thought maybe my algorithm was having issues with type ContentDisplay so i re-wrote my completeHandler function as follows:

function completeHandler(event:LoaderEvent):void {
    var image:Bitmap = LoaderMax.getLoader("photo1").rawContent;

The above new statement gives me bitmap. Now i run my module and guess what ? yay yepee it didn't run on firefox but ran on other browsers xD and this time i got null exception, yeah above statement returned null, weird rite ?? I was frustrated and cussing firefox xD. But accidently while doing just trial and error i added few parameters and viola boom bang dang it got running on firefox and all browsers xD. here is the new change that i made :

queue.append( new ImageLoader("img/photo1.jpg", {name:"photo1", estimatedBytes:2400}) );

well if u have noticed, i have added new parameter called "estimatedBytes". Yes, just this parameter solved above problem and again i was left scratching my head heheheh xD.


Yeah again i faced a little strange problem that i solved it. In my one of previous post i wrote about using movieclip with plane primitives of papervision and also accessing that movie. Now comes the main discussion of this post that is accessing movieclip from papervision plane.

Lets say i have attached a mouse listener to plane to which moviematerial is mapped. So when i click plane i want to do/manipulate the movieclip that is mapped to plane via moviematerial so code would look something like this:

private function planePressed(event:InteractiveScene3DEvent):void{
var moviemc=event.target.material.movie as Movieclip;
// do manipulation or changes on moviemc

the above snippet works, i mean u can access the movieclip on above do the later changes to it if u want.

But lets say there is no listener attached to the plane but later in program cycle i want to modify the movieclip attached to plane like applying blurr filter to it. Then i would do something like this:

var mc=my_papervision_plane.material.movie as Movieclip;
//apply blurr filter to mc

Well the above code didn’t work for me. In previous above event handler i traced event.target and it traced plane object, so it seems like ‘.material’ returned MaterialObject3D so i have to first downcast it to MovieMaterial separately and then try to access movie property on it. Here is the error:

So here is how is the stupid solution 😀

var mat=my_papervision_plane.material as MovieMaterial;
if(mat){//just being safe
var mc=mat.movie as Movieclip;

So that worked. But still i didn’t had to do that inside my event handler when i was accessing via even.target, maybe i am missing something out. Right now i am going through docs of papervision.


Hello  Flashers ,

Have you ever come across the dreaded “<error>” ?  If you have read on, if you haven’t you might wanna take a look at this.

Well  it started out like this………i was working on dynamic flash slideshow gallery. I was loading external images and paths were saved on xml file. Slideshow was working and running smoothly until i closed my browser window and received “Error #2044: Unhandled IOErrorEvent:. text=Error #2036: Load Never Completed.”.  Grrrrrrrrrrrrrr. When i closed my browser window i got this exception error on a window, here is the screenshot:

This error only comes when image was being loaded(preloader is shown during loading) and during that loading period if i close my browser exception error was being thrown. I knew the reason behind the error but didn’t knew the solution to handle it.

I didn’t knew what to. What was i supposed to do when error was coming on closing the browser ? I thought it was a browser issue. But there are lots of this kind of application out there and they doesn’t have this issue. So i have to do something about this “memory leak” thingy. So i found the solution for this and solution is to add the error handler to loader:

image_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);

private function ioErrorHandler(event:IOErrorEvent):void
//do your stuff

I hope it helped to those who faced same problem like me.


I am making a 3d portfolio site for my friend who is a photographer and graphic designer. I am very much enjoying developing it. I am using Papervision 3D for this project. So lets come to the objective of this post. There is a About me section and my friend wants the feature where she could edit the “about me” details through some dynamic editor like built in php. So basically i am giving my friend a basic editor features also with support of basic html tags to define the structure like “p b i br” etc. And there will be an xml file where all this content along with html tags will be written to. I’l be parsing this xml file from my as3 code and display it. Yeah there is a separate css file also for formatting the content but its not dynamic. So this is the objective and really i had problem with rendering content according to associated html tags.

Problem: I am rendering contents to TextField using its htmlText property and its styleSheet property for css. Every sentence starts with extra three or four spaces. With every ‘br’ tag comes extra 2 new lines. So basically i was having problem dealing with these extra space and extra new lines.

First i googled it and found many solution for removing extra spaces and new lines but nothing worked or maybe they weren’t working for htmlText or i don’t know the reason so i came up with my own solution by writing a code to eliminate extra spaces and extra new lines. Though my this code wasn’t fool proof but it worked to some extent as it removed extra spaces and new lines. But still it wasn’t 100 % perfect regarding alignment. Here was my code that i wrote to dissolve this problem:

var original:Array=contents.split("\n");
var original1:Array = this.contents.split(" ");
var tempStr:String = "";
for (var i:int = 0; i < original1.length; i++) {
   if (original1[i]=="") {
   original1[i] += " ";
   tempStr += original1[i] ;
contents = tempStr;

So what i am doing is splitting every word following new line into array indexes and joining to empty string. And in case of spaces i am doing same but i am restoring the spaces back that was there between words that is only eliminating first and last extra spaces.

This was working okie, i would say 95 % but not full perfect as few lines when rendered to TextBox had some very minor alignment issues so i had to come up with some other good solution.

But accidently i found the solution which i couldn’t find in google heheheh 😛 (maybe i didn’t searched properly). I use FlashDevelop for my coding, yeah its an awesome IDE. So i typed ” .”(period operator) after my textfield reference variable and list of methods and properties appeared. I was going through all and found this life saving property called “condenseWhite”. condenseWhite removes all extra spaces and new lines from html text if property is set to true. So simple solution and i was scratching my head and writing all those code to resolve this problem.

So bottom line if u are parsing html text in as3 and if you get extra spaces and new lines when rendered to TextField the just set the condenseWhite property to true. I hope it helps someone who face same problem like me.


I just came across this strange problem while writing a demo for car racing game on AS3. I don’t know how to start but please bear with me.
I have a button movieclip on a stage. It’s a “Play Game” button. When I click this button my game starts. So I press the button and game starts (also button is removed from the stage). Now I should be playing the game. But I could not play it. Why? Because my key press events are not getting fired, so I can’t drive my car. I had added the key listeners to stage but my events don’t respond. Then I mouse clicked on stage then viola my key press events are getting fired and suddenly I am able to drive my car. I scratch my head. Question marks appear over my head. I didn’t have the clue why this was happening? Here is the part flow of game code:

    //init codes
    //adding keylisteners to stage

So that is the flow. So when i enter startGame then somehow i am losing the focus on my stage since i am not able to get any response from any key events. But when i click on game screen/stage then my key events are working.
I didn’t found the valid reason behind it. I tried many things but couldn’t solve it. I googled it and found a simple solution on some forum. Solution is:

     //.................................................start game codes.................

“stage.focus=stage” was the solution i found but i still haven’t figured out the reason behind this stupid problem. What i could conclude is that my focus is still with the button that i had pressed and focus hasn’t bubble up back to stage. So anyone who knows the reason, please do explain it.