""

Tag Archive: Box 2d

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

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

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

I have been doing game development on android very recently (2 weeks) :D. And i bought samsung galaxy having android 2.1 to test my games and demos. I am pretty happy with the results and enjoying very much. Before this i had made games for j2me mobile devices and still making. Well anyway i am not discussing android game development here so i am coming to the primary focus of this post.

Physics. Yeah physics is phun and if decent physics is added to your game then it makes game more enjoyable, of course if gameplay design is good and fun. I have been playing with my own very very basic physics code(collision detection, collision response) that i have written for j2me. It is working fine in android after tweaking my code here and there. But i wanted more features so i thought to look for any decent free opensource physics engine for android. Unfortunately i didn’t get much success. There were some forums and tutorials where using Box2d with android was discussed. This site has shown the tutorial using JBox2d on android and is been discussed by the people there.

I am a big fan of Box2d. I have been using JBox2d and Box2d flash for my respective platform based game. Library had fulfilled my satisfaction and need. I have not tested JBox2d on android yet. I wanted to do few research on it before doing that. In few forums people complained that if using more than 5 bodies, it brings the FPS rate down and makes simulation very slow. I haven’t checked that but is going to write code to see if its true. I think it may depend on hardware device specification and capability because i have played Angry Birds on my samsung galaxy s and physics of game works just fine and smooth. I came across one site where they showed the graph on how much number of bodies/elements effect the FPS(frame rate) using Box2d and Chipmunk. Here it is.

So now i am going to write a simple code of falling polygons using Box2d on android and see the FPS and performance. I will post the results and my experience on next post ASAP.

Merry Christmas & Happy New Year
Gracias.

Well i would start by saying that Box2D Flash made my life so easy ๐Ÿ˜€ and Physics Is FUN ๐Ÿ™‚

I have been making physics based 2D platform games in Flash ActionScript 3.0 for just one past one month. yes i am newbie in Flash world. For Physics based game i chose Box2D Flash 2.1 and why did i chose Box2D Flash ?? cuz it had a good reviews from other developers and it was the first library that i stumble into via google haha ๐Ÿ˜€
But at the end it gets my job done much easier that i thought. Its very powerful library and meets my needs till now.

So i was playing around with the library by going through many tutorials, you’l get many on the net. Many of them were very very useful to me and got me started at instant.

Well now lets come back to the subject of this post: Using Movieclip with Box2D !! Please don’t get confused with the name of the post ๐Ÿ™‚ This post is about how i used movieclip from fla library or images with Box2D flash, at start i used to play with shapes like polygons and circles, collision between shapes and all that. But when i learned those things and wanted to make basic game simulation demo then i didn’t know how to use real Images with the library. I searched many tutorials but i didn’t get the way to use real images with the library. Then i stumbled into a forum where this topic has been discussed. So now here i am goint to tell how to use movieclip with library i.e instead of showing circle and polygons moving around and interacting, you’l be using movieclips ot bitmaps.

I’l assume that u know basic setup and use of Box2D Flash 2.1 because i won’t be explaining those things, i’l just explain how movieclip will be used. And maybe someone have better way to use it so please share it in comment.

First of all, for newbies like me, please go to this tutorial. It has good explanation of using Box2D and its concept. The Movielclip from fla that i am using here has been downloaded from here Adobe Article

1) Create the Shape definition for MovieClip that will be used (literally), its shape definition for the box2d shape.

var bodyDef:b2BodyDef=new b2BodyDef();
bodyDef.type=b2Body.b2_dynamicBody;
bodyDef.position.Set(SWF_HALF_WIDTH/PIXELS_TO_METER-1.5,4);

2) Create the body. And we are assigning the instance of Movieclip to body using SetUserData function. you could say we are associating Movieclip data to body. I don’t have other way to explain it. ๐Ÿ™‚ here texture is the instance of my movieclip that i created in fla file. Image is shown below

Moviclip from fla

var body:b2Body=world.CreateBody(bodyDef);
body.SetUserData(texture);

3) Now we create our shape.

var dynamicBox:b2PolygonShape=new b2PolygonShape();
dynamicBox.SetAsBox(2.1,2.1);

4)ย We can set various properties when we create the fixture.

var fixtureDef:b2FixtureDef=new b2FixtureDef();
fixtureDef.shape=dynamicBox;
fixtureDef.density=1;
fixtureDef.friction=1.0;
body.CreateFixture(fixtureDef);

5) Set the position of movieclip relative to the position of shape body that movieclip will represent

body.GetUserData().x = body.GetPosition().x*PIXELS_TO_METER;
body.GetUserData().y = body.GetPosition().y*PIXELS_TO_METER;

6) Add the moviclip

addChild(body.GetUserData());

7) I am calling update function on ENTER_FRAME

addEventListener(Event.ENTER_FRAME,update);

8] update function where physics world will update and object will interact

private function update(event:Event):void{
    var timeStep:Number=1/30;
    var velocityIterations:int=6;
    var positionIterations:int=2;

world.Step(timeStep,velocityIterations,positionIterations);

world.ClearForces();

for(var worldbody:b2Body = world.GetBodyList(); worldbody; worldbody = worldbody.GetNext()){

if(worldbody.GetUserData()!=null){

             worldbody.GetUserData().x = worldbody.GetPosition().x*PIXELS_TO_METER;
             worldbody.GetUserData().y = worldbody.GetPosition().y*PIXELS_TO_METER;
             worldbody.GetUserData().rotation=(worldbody.GetAngle())*180/Math.PI;

In above update function, inside for loop, i am iterating through world list for bodies and in each iteration i am checking if each body in world has movieclip/userdata associated. If userdata is not null then i am updating movieclip in this case so we are setting the position values of body shape to our movieclip in general and it will behave as shapes do. I hope i haven’t made u confused . I tried my best to explain this. It works.
Download Source Files

Gracias

I am Flash

Its been almost One month that i have been learning and writing Flash application with ActionScript 3.0. After getting familiar with ActionScript 3 and writing lots of program, i tried to venture into 3D. After googling some on doing 3D with ActionScript, i came across PaperVision3D. Its an awesome 3D engine. I enjoyed writing papervision app codes like 3d Carousel and Games. You can download the papervision library from here. There are lots of good papervision tutorials there out. They’l get you start with writing basic papervision programs quickly. I’l also post my work that i have been doing ๐Ÿ˜€

There is another library that i loved very much and made my life easy :D. Its a physics engine Box2D Flash. Its a port of c++ Box 2D. This is my first time attempt on Box2D library. When i started writing physics based flash game using Box2D Flash, i was very satisfied with the outcome. You can download the library from here.

Links to papervision tutorials that you would like to check out:
Basic starting tutorials: http://www.emanueleferonato.com/2009/05/08/papervision3d-for-the-absolute-beginners/
All good tutorial: http://papervision2.com/
Simple 3D carousel: http://papervision2.com/a-simple-papervision-carousel/
Loading 3d model using papervision: http://papervision2.com/loading-complex-models-v2/
Handling Basic 3D interaction events: http://papervision2.com/basic-interactivity/
Lighting and Shading: http://blog.tartiflop.com/2008/08/first-steps-in-papervision3d-part-4-lighting-and-shading/
Texture Mapping: http://blog.tartiflop.com/2008/08/first-steps-in-papervision3d-part-6-texture-mapping/
Basic Shapes and Texture Mapping: http://www.rozengain.com/blog/2007/04/05/papervision3d-tutorial-part-2-basic-shapes-movement-and-segments/

Links to Box2d flash 2.1 you would like to check out:
Getting Started: http://blog.allanbishop.com/box2d-2-1a-tutorial-part-1/
Beginners: http://www.emanueleferonato.com/2010/02/01/box2d-tutorial-for-the-absolute-beginners-revamped/
Complete Walkthrough of HelloWorld Code Example: http://plasticsturgeon.com/?p=295
Physics Based Game Tutorial: http://www.adobe.com/newsletters/edge/april2010/articles/article7/

Gracias.