Archive | Actionscript3 RSS for this section

Encapsulation : why?

Now, I remember, I had this question when developing my first framework. At some point in time, when developing your own framework of some kind, you must be asking the same question. The question is “Why I will make properties of a class private?! When everyone is capable of accessing it, why properties would be private ?”
This reminds me of my first dive into the object oriented programming in Java. All most all the books, explained that, all the properties of an object should be private with its getters and setters as public. I asked myself, it does not make any sense to write some more lines of code for the same thing. If at all, user needs to access my properties, I can make them public at the first place.
The answer was not clear at that point in time. But as I went along and developed some couple of more frameworks for my projects, the encapsulation part slowly made sense to me.
Encapsulation is not data hiding. Yes, you heard it right. Its not hiding the data. Its bundling the data with some methods to regulate the process, how those data can be manipulated.
Lets take an example, Ball is an object, which has to be moved across the stage. Well, in that case, we can write a Ball class and use it to move by changing the x and y position of it. Thats straight enough. Now, if there is a requirement that the Ball must be moved in straight line from left to right, then what happens. We comeback to our main file, or the stage file, or wherever we have used our Ball object to move. change the code and we are done. Impressive! In the process actually we are modifying something else, not the Ball Object. Though the requirement for Ball has changed, because of our way of coding, we have to modify some other class so as to fix the problem. There comes the solution of encapsulation. What if all the movement code are there with the Ball class. In order to move it, let there be a method named “moveIt()”

public function moveIt():void
{
//Do code for moving the ball from left to right
}

Now, all we need to do is, hide the ball movement code inside our Ball object. The calling object will just call the method named “moveIt()” of the ball object. Incase there is a requirement change, and now the Ball should move from right to left, there would be no worries as to where and how to change the code. The only thing which will change is the implementation of the moving ball code inside the “moveIt()” method. There may be a direction property of ball object, which will check the direction of movement of the ball. That also could be implemented inside the “moveIt()” method as below.

public function moveIt():void
{
//if the ball is moving from leftToRight
this.direction=”leftToRight”;
//Do code for moving the ball from left to right
if(this.x>=MaxWidth)//ball reaches the rightmost point
{
this.direction=”";//no direction now, as ball is stopped moving
// stop the ball
}
}

Similarly if requirement is to move it from right to left, the code will look as below

public function moveIt():void
{
//if the ball is moving from right To left
this.direction=”rightToLeft”;
//Do code for moving the ball from right to left
if(this.x<=0)//ball reaches the leftmost point
{
this.direction=”";//no direction now, as ball is stopped moving
// stop the ball
}
}

Now we can see that the private property “direction” can not be accessible from outside. but its only used inside the Ball object. So the data is encapsulated. We can still interact with it but not directly. The rules could be set as to how to interact through the public exposed methods.

Another example would be, suppose we have a property of an object, which is always a multiple of 2. But then we do not want our user to know that the property is always a multiple of 2. So we may expose the setter method as to take any integer, but internally we will be storing that as a multiple of 2. The code would be something like below

private var _myNum:int;
public function get myNum():int { return this._myNum; }
public function set myNum(value:int):void
{
this._myNum = 2*value;// we are not storing the user value directly
}

Now it makes a lot of sense to have all the properties as private. Only expose those with setters, which are really needed to be exposed. Another advantage is, any requirement change will just make us change at one place (if the value should be multiple of 3 instead of 2, we just change the setter).

Happy Flashing :)

Glimpses of Flash Platform Summit

Well, took me sometime but here are some of presentation videos, comprises of BCI demo by Alvin (@zhangyb).

Happy Flashing :)

Back from Adobe Flash Platform Summit

The meet is over and I must say, for me, it was a nice experience. It was the virtual media, the internet which allowed me to connect with so many people in past years. All the time I was thinking of meeting them in person and this meet allowed me to do that. Met with almost everyone I thought I will meet. But then missed some too.
Its the nexus, I was looking forward to and good that I made it.
The community is really vibrant and got inspired by a lot of nice talks.
Alvin (@zhangyb) delivered a talk on BCI ( Brain-Computer Interface ) with the demonstrations, on one of the demo, he changed the colour of an application with his thought.
Mrinal (@mrinal) was excellent with his explanations on the pixels, matrix and how they work on flash world. His demo comprised of effects like “genie effect” on Mac.
Arul (@_Arul) announced and demoed his new opensource framework, which will be available around next week.

Apart from the talks in the auditoriums, the most critical and influential talks happen outside and in very informal way. Glad to meet the never met before Vipin (ohh! people know him as @flashchemist :) ), Mark (@markadoherty), Arul (@_Arul), Mrinal (@mrinal), Abdul (@abdulqabiz), Mariam (@mariamdh), Hu Shunjie (@shinchi), Alvin Zhang (@zhangyb) and a lot many cool ones. Felt bad as I missed some too :( . For me it was the connection and glad that I made it to the meet.
One thing for sure, my avtar needs an update :) I have to go to people and an introduce myself as Saumya :) , I think for the same reason a lot might have missed me too, sorry for that to all and specifically to Saurabh Mathur(@sawrb).
Overall, it was a good meet for me to get connected. If you think about sessions only, then think again, most exciting things happens outside of it. And the best part is all the cool ones are most social ones too. One can reach out to anyone and start discussing at anypoint. Good to have a community like this.

Happy Flashing :)

Game Engines for Flash

Its been a while since I looked into the gaming side of the Flash. In the early days it were all hacks to get things done for an effect to happen. Now as the Flash platform is matured and put itself as a major player for game development, the complexity of the development also increased. Fortunately all the good things, which happened to the matured languages, is happening to Flash now. There are some nice frameworks and engines coming in. When game programming demands a completely different mindset and process, the conventional application development frameworks can not be fit in this place. People and companies have tried and ported the best game engines and physics engines to flash. Below is a list of 3 frameworks/engines , which are kind of setting themselves as the major gaming engines in Flash.

  1. PushButton Engine
  2. Flixel
  3. FlashPunk

All of the above engines are opensource and already showing a fan following and promise to deliver quality gaming.
Personally I have not yet tested anyone of these. Will update once do some hands on.

Happy Flashing

Adobe is hosting a free Media Player

Playing media will never be simpler than this. Adobe recently lunched a hosted service for playing back your media files. This is called Flash Media Playback , basically a media player hosted at Adobe. It is based on the Open Source Media Framework (OSMF). The full feature list is here. This has got a web configuration here. The point here is, one can just upload a video somewhere in the web and in the configuration, point the source to the respective URL. All that remains is copy-paste the generated code and you are ready with a media player, to play your video content.
The opensource version of the player is known as Strobe Media Playback and this is hosted at sourceforge. For those, who like to host their own media player, can download this and host it in the personal preferred location.
I took a test by implementing the Flash Media Playback. It took 2 mins to integrate a hosted f4v file in my server with the Flash Media Playback.
Peter Elst has already put in a plugin for wordpress to use Flash Media Playback.

Happy Flashing :)

FlexUnit4 mindmap

As of my first experience with Unit testing and Unit testing frameworks, I have been exposed to FlexUnit. The version I am using here is Flexunit4 and as a new comer for me everything is new. But FlexUnit 4 itself is a major version it seems. There are a lot of new additions to the framework. The best part is, it is now meta data driven as compared to previous inheritance concept. So basically one need to add metadata on top of the method names instead of making the testclass extend from some framework classes. Well, as a Robotlegs user, it certainly makes sense for me. And for anyone out there, if you understand how difficult it is to re-work on the classes which are tightly coupled to a framework, can certainly understand how flexible it is to work with just metadata.

Next thing is how to display my thought on FlexUnit to anyone? I got introduced by my current company to a Mindmapping software named XMind. Again an awesome software for its ppurpose. Quickly I put my thoughts on it and here is the result.

If anyone can fixup the mindmap for better explanation, I am putting the source here.

Happy Flashing

Global Error handler with Flash Player 10.1

With FlashPlayer 10.1 comes the ability to handle all the exceptions at one place, aka, Global Error Handler. This means a SWF can be made so that it does not pop-up usual error message dialogues, we generally see now a days with a lot many sites, if we have a debug version of the player. This simply does not mean we should ignore any errors in code. What does it mean is, we still have another gate to filter out any error messages from our application. There can be situation in a team environment, where someone can missout something and that will throw an error on runtime. Well, without further digging into the cause, lets dig into our point of handling the errors.
There is basically another property now to the “LoaderInfo” and “Loader” object. This property is known as “uncaughtErrorEvents”. The trick is to listen to “UncaughtErrorEvent.UNCAUGHT_ERROR” event on this property of the “LoaderInfo” and “Loader” object and handle it. Further more, if we completely want to supress the error dialogue box from poping out, “preventDefault()” must be called on the error handler.
Jumping to the code, add an event handler to the keyboard event like
this.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
On its handler try to remove a sprite from the display list,which is not yet present in the display list. The code is as below
private function onKeyDown(e:KeyboardEvent):void
{
var sp:Sprite = new Sprite();
this.removeChild(sp);
}
At this point, if we try and run our swf and press any key on our keyboard, the error dialogue will come up.(Keep in mind, this only happens if we have a debug version of the FlashPlayer)
Well, now this dialogue is very annoying if we are an user.  We can avoid this by handing the error on our GlobalError handler. In the beginning of the application listen for error on the LoderInfo object of the main application.
this.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, handleGlobalErrors);
Now, on its handler call “preventDefault()” method of the error event.
private function handleGlobalErrors(e:UncaughtErrorEvent):void
{
//this suppresses the error dialogue
e.preventDefault();
//application specific error handlers goes below

}
The next scenario is when we will be loading external SWFs into our main application. In this case just listen to the Loader objects “uncaughtErrorEvents” property for “UncaughtErrorEvent.UNCAUGHT_ERROR” event as below
var l:Loader = new Loader();
l.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, handleGlobalErrors);
l.load(new URLRequest(“myOther.swf”));
Thats all, now we have a Global Error Handler in place.
Note :
1. SWFs made for AVM1 with AS2 or AS1 can not be handled for errors on Global Error handler.
2. Even if the Error is handled in the Global Error Handler, the execution of the script does not continue on the call stack that caused the error.
Happy Flashing :)

SWF menus to load HTML pages

Before, beginning, here is the zip file containing all the source code for this example.

I thought it was easy all the time. But it is really easy, if one knows the below “AllowScriptAccess“ script parameter in HTML/javascript. This parameter is in the OBJECT and EMBED tags of HTML, by which FlashIDE generally embeds our SWF in the HTML ( If not embeded by SWFObject by us manually, then also we need to make these settings  ).

<param name=”allowScriptAccess” value=“always” />

By default, when published from FlashIDE, the value for this parameter is “sameDomain”. This should be something like

<param name=”allowScriptAccess” value=“sameDomain” />

The real deal  is, even if there is no param in a HTML page with “allowScriptAccess” , the default value it takes as “sameDomain”. That means, the SWF and HTML must be from the same domain. That makes it difficult to test this locally. One has to upload the HTML and SWF to a server and check it.  Well, if we change it to “always” like

<param name=”allowScriptAccess” value=“always” />

our SWf file can now communicate with any HTML page.

Once we know our settings, we need to know the API to call. The Class that makes actionscript-javascript communicate is known as “ExternalInterface“. This is in the package “flash.external.ExternalInterface“. All we need to do is call a javascript function from actionscript as follows

ExternalInterface.call(‘callFromFlashMenu’, btnName);

In the above call, we are calling a function defined in our HTML page as below

<script type=”text/javascript”>
function callFromFlashMenu(menuName)
{
alert(menuName);
}
</script>

This function takes one string as input and just alerts it to the user. This parameter we are sending from actionscript as the second parameter as you can see it ExternalInterface.call(‘callFromFlashMenu’, btnName);

Taking this concept forward, we will be making a menu in Flash and send the button names to the javascript function. This will make our javascript know about the button we have clicked in our SWF. Once button name is known to javascript, we can have a validation and change the HTML page on the container. Now what is the container? Well, in our HTML page, we will have an “iframe”, which can display any HTML page. The code would be

<iframe id=’htmlSrc’ src =”http://www.saumyaray.com” width=”600″ height=”300″>

<p>Your browser does not support iframes.</p>

</iframe>


As you can see, iframe has a property named “src”, which takes a html page URL, as its parameter. We can send in whatever HTML page URL, we want to display in this container. Even we can change the size of the container. So thats it, we already have the parameter from the actionscsript and now depending upon the button name we can change the “src” property of the “iframe”. The full scripts, along with the FLA is here for you to download and try.

The javascript function would look like

<script type=”text/javascript”>

function callFromFlashMenu(menuName)

{

if(menuName==’btnOne’)

{

document.getElementById(‘htmlSrc’).src=’http://www.yahoo.com’;

}else if(menuName==’btnTwo’){

document.getElementById(‘htmlSrc’).src=’http://www.bing.com’;

}else if(menuName==’btnThree’){

document.getElementById(‘htmlSrc’).src=’http://www.google.com’;

}

}

</script>

Hope that helps :)

Happy flashing

Flash CS5 and dynamic display object initialisation problem!! (added after first comment: should be “my problem” rather than “problem”)

[ added after first comment : I am adding this in the beginning for not to make a fire out of the post. Well, the problem is actually on my side and not Flash CS5. I have a movieclip whose registration point is buttom-left rather than default top-left. So when adding it to the stage with "new myClip()", it is getting added to the stage but then it stands upward from stage origin. This at the first glance to the stage makes no sense as no one can see anything above the stage. Instead of looking into this option I dig up the whole lot of other things making me believe that the problem is with Flash CS5 visual object initialisation.

I apologize, if any of you got caught by the title.

Anyway, as far as my study went regarding this subject, I do not regret as it gave me some true insights about the SWF loading with TLF RSL issue.

Here follows the original post ]

Well, this came to me as a surprise as I was breaking down a FLA into parts and getting assets from them. This was working perfect since Flash CS4. So I was going ahead with confidence that it will work perfect in Flash CS5 too !!  But it is not the case. Seems like Flash CS5 behaves very differently while initialising the display objects.

First, lets go through the links which people have already found.

After all these readings, it seems if I use one of these methods, its safe for me to go ahead. So I tried merging the TLF engine in my FLA (the easiest of all solutions).
But that also does not help me either. Geting definition from the SWF is working but the display objects do not get rendered!!
So, I continue digging it.  This time, I wanted it to be really simple. Now my target is to just instantiate a library item in the same FLA stage. Made an FLA with a library symbol named “Box” and the class name  ”BoxClip” (with “Export for Actionscript” and “Export in Frame 1″ ticked). Then in the first frame I have the code
var box:BoxClip=new BoxClip();
this.addChild(box);

To my surprise nothing rendered in stage!! And no errors given. Well, then thought may be I will make a class for it and see if that makes me render my object. So going ahead I made a “BoxClip” class which extends “MovieClip”. Linked it to the library symbol and tested movie. This time too it does not render my library clip. Going forward, I added a component provided in FlashCS5. And the code is modified as below
var b:Button=new Button();
this.addChild(b);

var box:BoxClip=new BoxClip();
this.addChild(box);

This time the Button component got rendered but still my library clip does not render. Finally converted my clip to a compiled clip and tested the same thing to get the same result.
Well the last option I took is changed the FLA format to new XFL format with a hope to render my library clip, but to get the same old result.
Its not that the library symbol definition is not getting into the environment, its the rendering of the display object thats the problem. For when I trace out as below
var box:BoxClip=new BoxClip();
this.addChild(box);
trace(this,box,box.visible);
the output is as follows
[object MainTimeline] [object BoxClip] true

So the object is getting created, its visibility is true. And well its being added to the display list too. As when trying to see the numChildren, it counts the object I have created dynamically.
Lastly I thought might be stage.invalidate() will help, but that also does not help here.
Hope, this helps someone out there.
Good night.

FLA compilation/publishing utility version 2

Well, this is just to make a little update to the utility I have made earlier for publishing the FLAs. The old utility code I never liked as a project, so ended up re-writting it again from ground up. Since the AIR SDK final verison is out, I have to compile it against the new SDK too.

The windows version of the utility is available here.

The new code is now taking advantage of Robotlegs framework and De MonsterDebugger. So if, you want to make your own utility on it, make sure you have the libraries.

One thing for sure is, I liked Robotlegs framework. After my earlier experience with other frameworks, I loved MATE the most (At that time Robotlegs was not born :) ) and the next thing is Robotlegs. Not only the framework is swift, but the community behind it is vibrant and the docs are just to the point. Good work guys.

Happy Flashing :)

Follow

Get every new post delivered to your Inbox.

Join 499 other followers