""

Tag Archive: as3

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.

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 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");
contents=original.join("");
var original1:Array = this.contents.split(" ");
var tempStr:String = "";
for (var i:int = 0; i < original1.length; i++) {
   if (original1[i]=="") {
       continue;
   }
   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.

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