Wwwebber's Blog

Box2d 2.1 How to use a b2Controller

Posted in actionscript 3, Box2d by wwwebber on July 9, 2010

Box2d 2.1 brought some awesome improvements
1) improved class structure.
2) buyouncy support
3) a set of Controller Classes that are well described by the docs as ” a convience for encapsulating common per-step functionality.” (read about them here)

These improvements were actually worth the fact that none of your prior Box2d code (and I mean none) would compile with the new class structure.

If you used earlier versions of Bo2D, you already used something like these controllers–the Gravity Vector that you passed to the world object at construction.
This was a b2Vec2 (the gravity) that the world applied to all non-static objects. Ie the walls wouldn’t be affected by the gravity vector but all the moving objects would be affected by a constant force downwards (unless your gravity had an unusual orientation)

There are several types of controllers and they all extends b2Controller . The TestBuoyancy class that comes with the TestBed shows an example of how to use the b2BuoyancyController .

All of the controllers have the following methods

AddBody(body:b2Body):void
RemoveBody(body:b2Body):void

I was interested in using a b2ConstantAccelController. There aren’t really any examples out there for this (at least that I could find) so here’s how easy it is to implement a b2ConstantAccelController–which will just apply an additional vector each time step to any bodies added to that controller.

Now, unlike the GravityVector you can arbitrarily add and remove objects from the controller. How could this be useful? Imagine that you have gusts of wind blowing sideways…you can add your objects to a Contoller and have them pushed sideways…then when the wind passes you could remove them from that controller.

How to create a b2ConstantAccelController :

//construct object and its acceleration vector
var myAccelController:b2ConstantAccelController = new b2ConstantAccelController();
const WIND_VEC :b2Vec2 = new b2Vec2(10,0);
//associate controller with vector
myAccelController.A = WIND_VEC

Henceforth, all b2bodies that are stored in myAccelController will have the WIND_VEC applied to them during the b2World.step() function .. you don’t have to do anything else except add and remove bodies to the controller.

//now let’s add something to the Controller
myAccelController.AddBody(someB2Body);

…when you want to remove the body
myAccelController.RemoveBody(someB2Body);

Advertisements
Tagged with: ,

Actionscript 3 Tween Library Skinner’s Gtween vs Greensock’s tweenlite

Posted in actionscript 3 by wwwebber on July 5, 2010

Just wanted to add a little extra feed back for anyone who is currently trying to decide on an Actionscript 3 tween library. There are many other to choose from. I spent some time over the last month playing with both Grant Skinner’s GTween library and GreenSock’s TweenLight library . In a nutshell, you can’t go wrong with either one. Both are awesome and I’m glad someone did almost all that heavy lifting!

However, after using both libraries over the course of the development of my most recent online maths games Rj The Robot on the topic of how to combine like terms.

First off, why both libraries ROCK!
-Awesome levels of customization of tween types (sinusodal, Bounce etc..) the differences here are small. At the time of this post, Greensock has some that the GTween library does not .
– Optimized performace.

How they Differ

Object Model
Greensock— You can use either static based methods to create tweens or use good old OOP to create tween objects.
GTween –it uses an object model, though a static based interface is also available

ie–they are pretty much the same here.

Visualizers
Greensock wins this–it comes with an awesome component that let’s you visualize tweens and will actually output the code needed to create the tween! Go Greensock (see what I mean here)
GTween–Do not think anything like this is provided.

Events
Greensock– TweenLite does not include an event system. However, if events are important to you then you just use GreenSock’s TweenMax (also free).
GTween– has a great event system.

Error reporting
Greensock– Hands down wins in the experiments I ran. If you pass Greensock a null object, it will throw an Error reporting the null reference.
GTween– In my tests, Gtween silently did nothing when I tried to tween a null object.
The winner here is clearly the Greensock library. Addendum: It turns out there is a reason for Gtween accepting null objects –read comments below.  That  said, Greensock allows the same chaining of events but reports null pointers.

In the end, you really can’t go wrong with either library. They both support object oriented syntax, chaining of tweens,and event dispatching and listening (Greensock only does this with the TweenMax..which is also free). Greensock does have a few extra tween types , the awesome visualizer as well as some amazing plugins –all of which led me to go with using Greensock.

If I you know of any other differences that I missed (and I know there must be many), please fire off a quick comment.

Using Actionscript to make Subscripts with Flash’s Text Layout Framework

Posted in actionscript 3 by wwwebber on June 5, 2010

Here’s a quick post on on some new Actionscript functionality that takes advantage of Flash’s new Text Layout FrameWork to create subscript and superscipt in the new types of text fields that you can create–These new things aren’t the TextField() that you are used to but rather are part of this whole new, much more sophisticated framework.. I used Flash CS5, but this should work with CS4 also. Apparently, the Text Layout Framework (which is just a component that you can install with the extension manager) will work with CS4.

This post will show you how to use Actionscript to perform this task. There are already lots of videos up on web showing designers how to use the Flash IDE to do this..so here’s how to code it.

What our code will produce:

I have made several math based flash programs, and it has always been a pain in the butt to deal with exponents and subscripts. It has definitely been a long time coming–the ability to create sub and superscripts in a Flash. Now with the new TextLayout Framework you can do all sorts of things including subscripts!. I needed to learn how to do this for a new maths game I was working on Rj The Robot-Since this was a math game, I needed to be able to write exponents in dynamic text fields…so let’s make some subscripts in Flash!

Just Tell me the Steps

Step 1) Download The Text Layout Component here (http://labs.adobe.com/downloads/textlayout.html) Note: do not install the ‘open source’ version, go down the page a bit to get the “text layout component

Step 2)
use the Flash Extension Manager to install the “Text Layout Flash Component.mxp” file…and then restart flash.

Step 3) Open up a Flash File , then open up the components panel (window-> components) and open up the “standard components” and drag an instance of the “textlayout” component onto the stage. (After you have done this you can actually delete the component from the stage…we just needed to make sure the component was in our library…I assume you could also just drag the component directly to the library to achieve this )

Ok, now you can use all of the cool text layout features that we will need to be able to make a Subscript in Flash.

Step 4) Now a bit of Actionscript. I am not going to go over all of the details of how the Text Frame Work works(the two links below explain the framework in greater detail).

Download the Source Code here

Good links on TextLayout
Adobe Docs
link 1
link 2

Here’s the code for Main

package
{
import flash.display.LineScaleMode;
import flash.display.Sprite;
import flashx.textLayout.elements.ParagraphElement;
import flashx.textLayout.elements.SpanElement;
import flashx.textLayout.elements.TextFlow;
import flashx.textLayout.formats.CharacterFormat;

import flash.display.DisplayObject;
import fl.controls.TextLayout;

/* textLayout_flash is the base class for the Text Layout component. If you bring up the properties on the TextLayout Component in the library, you will see this.*/

public class MainTxt extends Sprite
{

public function MainTxt()
{

var myTextComponent:TextLayout;
// Instantiate the textLayout_flash class to create a TextLayout Component.
myTextComponent = new TextLayout();

// Add the new component to the Stage.
var myTextComponentOnStage:DisplayObject = addChild(myTextComponent);
// Get the Text Flow from the TextLayout Component.
var textFlow:Object = myTextComponent.textFlow;
var span0:SpanElement = textFlow.getFirstLeaf();
span0.text = “E=MC”;

//get reference to ‘root’ ParagraphElement of the TextFlow
var rootParagraphElement:ParagraphElement = textFlow.getChildAtIndex(0);

var span2:SpanElement = new SpanElement();
span2.text =”2″;
rootParagraphElement.addChild(span2);

var span3:SpanElement = new SpanElement();
span3.text =”\n\nLog”;
rootParagraphElement.addChild( span3 );

var span4:SpanElement = new SpanElement();
span4.text =”2″;
rootParagraphElement.addChild( span4);

var span5:SpanElement = new SpanElement();
span5.text =” = 3″;
rootParagraphElement.addChild( span5 );

var cf:CharacterFormat = new CharacterFormat(textFlow.characterFormat);
cf.fontSize = 20;
textFlow.characterFormat = cf;

var superScriptFormat:CharacterFormat = new CharacterFormat(textFlow.characterFormat);

superScriptFormat.baselineShift = flashx.textLayout.formats.BaselineShift.SUPERSCRIPT;
span2.characterFormat = superScriptFormat;

var subScript:CharacterFormat = new CharacterFormat(textFlow.characterFormat);
subScript.baselineShift = flashx.textLayout.formats.BaselineShift.SUBSCRIPT;
span4.characterFormat = subScript;
}

}

}

Comments Off on Using Actionscript to make Subscripts with Flash’s Text Layout Framework

Box2d 2.1 b2world.QueryPoint() and iterating over a b2fixture list

Posted in actionscript 3, Box2d by wwwebber on May 20, 2010

In version 2.1 (and earlier I believe) of box2d objects are stored in linked lists. A common task will be iterate over one of these linked lists. For instance if you want to iterate over a body’s b2fixture linked list. In my case, I had the following problem: I was making a kids math game on how to combine like terms called Rj The Robot , and I only wanted the robot to jump if it was standing on a ‘floor’ shape. Now all ‘foors’ in the game had a string attached to their b2fixture called ‘is_floor’. Below is some code that demonstrates how floor bodies, shapes and fixtures are creating. Note: if you don’t know what a b2fixture is read this.

//bottom wall
var bottom_wallShape:b2PolygonShape = new b2PolygonShape();
var bottom_wallBd:b2BodyDef = new b2BodyDef();
bottom_wallBd.type = b2Body.b2_staticBody;
var bottom_wallBody:b2Body;
bottom_wallBd.position.Set(halfOfStageWidth /PIXELS_PER_METER , halfOfStage*2/ PIXELS_PER_METER- .5 );
bottom_wallShape.SetAsBox(ground_width, ground_height);
bottom_wallBody = myB2World.CreateBody(bottom_wallBd);


var fd:b2FixtureDef = new b2FixtureDef();
fd.friction = 1 ;
fd.shape = bottom_wallShape;
fd.userData = 'is_floor';
bottom_wallBody.CreateFixture(fd);


Now, I wanted the hero to be able to tell if it was standing on a shape whose b2fixture had the string ‘is_floor’ as its userdata. The solution is to use the b2World.QueryPoint() function . This function takes the form of myb2World.QueryPoint(callbackFunction, someB2Vec) where the someB2Vec is the point to check.  In the picture below I was sending the red dot, called heroFootPoint in my code, to the function. Below is the full code explained in the comments
//get hero's center point
var currentCenter:b2Vec2 = _body.GetWorldCenter();
heroFootPoint.x = currentCenter.x
heroFootPoint.y = currentCenter.y + 1.43    //add 1.43 so point is below Robot  foot;
var bIsOnFloor:Boolean = false;             //assume not standing on floor

function bOnFloorFixture(fixture:b2Fixture):Boolean    //call back function
{                                                                                                               //this call back function
var body:b2Body = b2Fixture(fixture).GetBody();            //get body of current fixture
var bsFixture:b2Fixture = body.GetFixtureList();
while (bsFixture != null )                                                                 //it
{
if (bsFixture.GetUserData() == ‘is_floor’)                  //found a fixture whose userdata is ‘is_floor’…ie are standing on the floor
{
bIsOnFloor = true;
return false;                                                                           //return false so that we don’t continue iterating over the list
}
bsFixture = bsFixture.GetNext();                              //if we got here we didn’t yet find a fixture with ‘is_floor’ userdat..

}                                                                                              //so see if body has another b2fixture attached for checking

return true;                                                                                    //callback returns true means that the queryWorld() function will check next b2Fixture at heroFootPoint
}
myB2World.QueryPoint(bOnFloorFixture, heroFootPoint);               //start queryPoint()…check all fixtures overlapping heroFootPoint

Comments Off on Box2d 2.1 b2world.QueryPoint() and iterating over a b2fixture list

Bitmapdata .disose()

Posted in actionscript 3, bitmapdata, fraction games, math games by wwwebber on November 30, 2008

This is just some venting…I am working a fraction game..i’ve tentatively called “Fraction Wars”..basically you blast up equivalent fractions. Anyway, I’m using a fair amount of blitting ala 8 bit rocket style. I decide to create and cache some text animations that use this blitting technique. The logic is that I would cache all the text animations that were likely to occur during the more intense parts of the game and then just blit them to the main canvas, a single bitmapdata object that spans most of the screen. (for in between levels when not much action was occuring, I used regular old text fields and transitionmanagers).

The morale of my wasted time is that bitmapdata’s dispose() method is DESTRUCTIVE. Only use it if you don’t need ANY reference that given bitmapdata. I knew this before today , just didn’t see how it

I wasted more time than I care to share over the following embarrising fact that I had a timer loop that

1) created new bitmapdata by drawing from a text field
2) store bitmapdata in a slot in an array
3) before moving on to the next iteration of the timer, I called .dispose() on the new bitmapdata

I know it seems obviuos now

Comments Off on Bitmapdata .disose()

Randomize Elements in an Array

Posted in actionscript 3, array by wwwebber on November 28, 2008

I had to rewrite some code that randomized elements in the new Vector class (had written the code below to randomize array elements)and thought I’d post both the old array randomizer() here. nothing fancy at all…just thought might be useful to someone.

var myArray:Array =[1,2,3,4,5,6];

function randomize(arr:Array):Array{
var originalA:Array = arr;
var newA:Array=[];

while(originalA.length > 0){
var index:int = int(Math.random() * originalA.length);
var element = originalA.splice(index,1);
//splice returns an array.
newA.push(element[0]);

}

return newA;

}

trace(randomize(myArray));

Note: the splice() method of the array class actually returns an Array made up of the elements you’ve spliced out of the original array. This is why we need to push element[0] into the new randomized array.

Comments Off on Randomize Elements in an Array

Loading External BitmapData into Vector of Type BitmapData

Posted in actionscript 3, bitmapdata, flash player 10, vector by wwwebber on November 22, 2008

I’m working on a math game that requires many external images to be loaded into Actionscript 3’s new Vector class (typed array) . It took me a bit of experimenting to determine how to properly load external images into a Vector of type BitmapData. Before the new the typed arrays of our new Vector class, I didn’t have to worry about the type of the data that I was storing (arrays can handle any type)…now, it’s a whole new ball game

. In the end, you just cast the content of the loader object to a Bitmap then access that Bitmap’s “.bitmapData” property…see a simplified version of my code below.


//Here’s my BitmapData Vector
var explosionVec:Vector. = new Vector.();

//load external png
var _loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded,false,0, true);
_loader.load( new URLRequest(“bath/To/Image/explosion.png”));

//
function loaded(e:Event):void{
//cast content to bitmap
var bmp:Bitmap = Bitmap(_loader.content);
//store the bitmapData from the Bitmap!
explosionVec[0] = bmp.bitmapData;

}

Comments Off on Loading External BitmapData into Vector of Type BitmapData

Vectors! Typed arrays come to Actionscript 3

Posted in actionscript 3, flash player 10, vector example by wwwebber on November 20, 2008

Finally got my hands on CS4… one of the main new new perks of the Actionscript is the new Vector class (nothing to do with physics or vector graphics)…these are good old typed arrays in the style of C++ or Java.

Basics of the Syntax

//create a Vector and call it vec

var vec:Vector. <int> = new Vector.<int>();

now “vec” can only store ints! This allows for Type-safety in your code, and potentially performance gains.

to add an object to a vector just call .push()
//the next line adds the int ‘3’ to the vector
vec.push(3);

Much more info over at Senocular

Comments Off on Vectors! Typed arrays come to Actionscript 3