""

Tag Archive: 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.

Gracias

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:

‘http://ajax.googleapis.com/ajax/services/language/translate’+’?v=2.0’+’&q=’+escape(my_input)+’&langpair=’+’es’+’%7C’+’en’

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:

package 
{
	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
			
			initGUI();
			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.url='http://ajax.googleapis.com/ajax/services/language/translate'+'?v=2.0'+'&q='+escape(fromInput.text)+'&langpair='+fromLanguageCombo.selectedItem.data+'%7C'+toLanguageCombo.selectedItem.data;
			request.method = URLRequestMethod.GET;
			
			var loader:URLLoader=new URLLoader();
			loader.addEventListener(Event.COMPLETE,messageSent);
			try 
			{
				loader.load(request);
			} 
			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.

Gracias.

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 😛

Gracias.

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)) {
		contact.GetFixtureB().GetBody().SetAwake(false);
		contact.GetFixtureB().GetBody().GetUserData().destroy();
	}
}

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()) {
			world.DestroyBody(worldBody);
		}

                //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

Gracias

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
queue.load();
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.

Gracias.

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.

Gracias

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.

Gracias

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:

buttonClicked(){
    initGame();
    startGame();
}
initGame(){
    //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:

startGame(){
     stage.focus=stage;
     //.................................................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.

Gracias

After hours of hard work finally i made my pinball flipper working properly with box2d flash. Yeah i had a pain of time while making my flipper work properly 😀

So before writing points on how i made my pinball flipper, i wanted to make clear that this is the way i did it so it may not be better way. If anyone has got better technique then please pretty please share with us hehe 😀 Thanks.

So first thing first, i created a rectangle i.e polygon set as box, this rectangle was my pinball flipper. Now i wanted to move/rotate the flipper within given limits as it does in any pinball game. Yeah i didn’t mention that i chose box2d flash as it supports all my physics needs and does its job pretty good so i would not have to write the collision and basic physics from scratch.

Now next step, i had to rotate flipper around a pivot point near the end of flipper, by default my flipper would rotate around its center which i didn’t wanted to happen. Second, i wanted to make my flipper aka polygon to be dynamic body so that it would react to gravity. So if i made my flipper dynamic then my whole flipper would fall down acting to gravitational force, this i didn’t wanted to happen either. So i needed a way to fix my flipper to a pivot point around which my flipper will rotate and also my flipper would react to gravity provided flipper should be attached to that pivot point. I hope you understand what i am saying 😀
Next step, i had to restrict the rotation of flipper because i didn’t wanted my flipper to cover whole 360 degree circular motion.

Well now the solution of above, i would say again that i had a pain in my ___ to make it work. But when i found the solution and implemented it, it looked easy and smooth like butter or cheese hehe 😀

Ok so what i did is i created a small circle which looked like a dot, this circle dot will act as my pivot point. Now my polygon flipper will be attached to this circle dot, which is static body, it means my circle dot would not react to gravity. So coming to bottom line, i created a revolute joint between the circle dot and polygon flipper. With this, my circle dot will act like a hinge and flipper will be rotating around that hinge and also flipper would react to gravity. Now just restriction for rotation of flipper is left which is done by setting lowerAngle and upperAngle property of revolute joint. Another important thing is setting enableLimit to true.

I assume you know Box2d so not explaining all codes in details. Now code of setting up whole flipper and hinge pivot point:

sawDef=new b2BodyDef();
sawDef.type=b2Body.b2_dynamicBody;
sawDef.position.Set((Metrics.HALF_WIDTH+40)/Metrics.PIXELS_TO_METER,18);
			
sawBody=world.CreateBody(sawDef);
			
var sawBox:b2PolygonShape=new b2PolygonShape();
sawBox.SetAsBox(1.1,0.2);
			
var sawfixtureDef:b2FixtureDef=new b2FixtureDef();
sawfixtureDef.shape=sawBox;
sawfixtureDef.density=2;
sawfixtureDef.friction=0.;
sawBody.CreateFixture(sawfixtureDef);
			
localCenter = sawBody.GetWorldCenter();
localCenter.Add(new b2Vec2(25/Metrics.PIXELS_TO_METER,0));
			
var circleBodyDef:b2BodyDef= new b2BodyDef();
circleBodyDef.position.Set(localCenter.x,localCenter.y);
circleBodyDef.type=b2Body.b2_staticBody;
			
var my_circle:b2CircleShape=new b2CircleShape(1/Metrics.PIXELS_TO_METER);
var my_fixture:b2FixtureDef = new b2FixtureDef();
my_fixture.shape=my_circle;
var circle_body:b2Body=world.CreateBody(circleBodyDef);
circle_body.CreateFixture(my_fixture);
			
revoluteJointDef = new  b2RevoluteJointDef();
revoluteJointDef.Initialize(sawBody, circle_body, localCenter);
revoluteJointDef.upperAngle = .6;
revoluteJointDef.lowerAngle = -.6;
revoluteJointDef.enableLimit = true;
revoluteJointDef.maxMotorTorque = 10.0;
revoluteJointDef.motorSpeed = 0.0;
revoluteJointDef.enableMotor = true;
world.CreateJoint(revoluteJointDef);

Note: Metrics.PIXELS_TO_METER is 30 (in box2d length is measured in meters)

I have created a polygon body(sawbody) and small circle as hinge point (circle_body). Then i am creating a revolute joint between polygon and circle by fixing circle near the end of polygon represented by variable localCenter(b2vec2). Now i want to set angle limit for the rotation of flipper say 35 degree, it means flipper will cove only 35 degree rotation. So i am setting upper angle and lower angle to 0.6 and -0.6 respectively because it takes radians as value and 35 degree is equal to approx 0.6 radians. Now you have to set the enableLimit to true.

Good posts on Revolute Joint: Emanuele’s and Allan Bishop’s

Here is the code how i am using the flipper:

private function update(event:Event):void {
	var timeStep:Number = 1 / 30;
	var velocityIteration:int = 6;
	var positionIteration:int = 2;
			
	world.Step(timeStep, velocityIteration, positionIteration);
	world.ClearForces();
	world.DrawDebugData();
			
	input();
}

private function input() {
		if (RIGHT) {
			sawBody.ApplyTorque(150);
		}
		else if (!RIGHT) {
			if(sawBody.IsAwake()){
					sawBody.ApplyTorque( -150);
			}
		}
			
		if (LEFT) {
			sawBody2.ApplyTorque(-150);
		}
		else if (!LEFT) {
			if (sawBody2.IsAwake()) {
				sawBody2.ApplyTorque(150);
			}
		}
	}

I hope this posts helped u. If u have more good techniques then please share.

Happy Valentines Day
Día del Amor y la Amistad
Gracias

Busy Busy with stacks of projects on hand. I am learning lotsa things while working on them. I love learning new stuffs and programming is my passion. So one project i am working on is flash web page. So i thought to make a 3D flash site with some cool effects. I chose papervision 3D for my project. I am happy with the outcome till now.

But anyway i am here to share some small problems that i face during the development and how i solved it. There must be newbies like me out there who might face this problem :D. So here i’l share how i faced a problem regarding playing movieclip animation mapped to 3d object on papervision 3d.
I had never used movieclip on my previous papervision projects, rather i used bitmaps for graphics. In my current 3d flash site project i was required to use some movieclips also. I opened the papervision documentation and found something called MovieMaterial for creating a texture from my movieclip instance in fla file. Using MovieMaterial is simillar to using ColorMaterial and BitmapFileMaterial. Here i will just be talking about MovieMaterial.
MovieMaterial creates a texture from movieclip to be mapped to 3d object like cube. So i created a MovieMaterial :

materialFront = new MovieMaterial(movieclip_instance1);
materialFront.smooth = true;

movieclip_instance1 is a instance of movieclip in fla library. So i am getting material/texture from the moviclip. So i created other materials for other faces of cube. Then i added all materials to the MaterialList:

cubeMaterials:MaterialsList = new MaterialsList();
cubeMaterials.addMaterial (materialFront, "front" );
cubeMaterials.addMaterial (materialBack, "back" );
cubeMaterials.addMaterial(materialTop , "top" );
cubeMaterials.addMaterial materialBottom, "bottom" );
cubeMaterials.addMaterial(materialLeft, "left" );
cubeMaterials.addMaterial(materialRight, "right" );

Now i just used this matriallist to the cube:

cuboid = new Cube(cubeMaterials, 750, 5, 500, 10, 10, 10);

So movieclip is mapped to all the faces of cube. So this is done. But those movieclips that i mapped were just a single graphics, it didn’t have frame animations inside movieclip. So i mapped a movieclip having animation into it to cube using same above steps and codes but viola, movieclip animation wasn’t playing, just first frame was getting rendered at the face of cube. So this was quite a problem for me because i wanted to render movieclip animation for giving nice effects.

I just googled on this topic and found the solution. I went to papervision documenation again and opened the MovieMaterial doc and looked at the constructor parameters. The last parameter in the MovieMaterial constructor specifies the additional properties associated with the movieclip. Default value is false. So i modified a line of code:

materialFront = new MovieMaterial(movieclip_instance1, true, true);

The second parameter specifies whether movieclip is transparent . Last parameter is what i needed to solve my problem, I passed it true saying i have animation into my movieclip and i want it to play when rendered. So viola movieclip animation was playing and i had a stupid grin on my face 😀

Gracias.