When I first created QuickBox2D I simultaneously developed a simple editor to aid in the creation of complex simulations. The result is very alpha and should be used cautiously. There is no UI, it is entirely key controlled. It generates actionscript files that can be copy and pasted into working simulations. It also has a preview mode for previewing simulations as you develop them. This is by no means a full featured editor, there is a good deal of work to be done on it. I am releasing the code as a simple zip for people who would like to develop it further. If there is enough interest I’ll create some kind of code repositiory, but for now I’m just releasing the below zip.
I may post further instructions for the editor in the future… Remember to save your work frequently and to create new versions for every change that you make to a file.
Suggested Features:
Simple GUI
Base64 encoding for get string
Known Issues:
Making joints that don’t touch things can break the preview app.
So I have a QuickBox2D editor that I’ve had since the earliest version of QuickBox2D. It is really pretty buggy and imperfect. I’m wondering if I should release it even though it’s really buggy… my main issue is I won’t be able to guarantee that it is a safe editor to use for real projects.
[SWF(width = 800, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
stage.frameRate = 60;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
sim.start();
var output:TextField = new TextField();
output.text = "Click anywhere to add points to a polygon. Hit any key to test.nn";
output.x = output.y = 50;
with(output) width = 300, height = 400, border = true, selectable = true, wordWrap = true, multiline = true;
addChild(output);
function display(str:*):void{
output.appendText(str.toString() + "n");
}
var points:Array = [];
var poly:Shape = new Shape();
addChild(poly);
stage.addEventListener(MouseEvent.CLICK, onClick);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
function onClick(evt:MouseEvent):void {
if (points.length == 0){
poly.graphics.beginFill(0xCCCCCC);
poly.graphics.lineStyle(1, 0xFF0000);
poly.graphics.moveTo(mouseX, mouseY);
}else{
poly.graphics.lineTo(mouseX, mouseY);
}
poly.graphics.drawCircle(mouseX, mouseY, 2);
points.push(mouseX / 30.0, mouseY / 30.0);
}
function onKeyPressed(evt:KeyboardEvent):void {
// average all points
var avgX:Number=0
var avgY:Number = 0;
for (var i:int = 0; i<points.length; i+=2){
avgX += points[i];
avgY += points[i + 1];
}
avgX /= points.length/2;
avgY /= points.length/2;
avgX = avgX;
avgY = avgY;
// subtract averages and fix decimal place
for (i = 0; i<points.length; i+=2){
var yp:int = i + 1;
points[i] -= avgX;
points[yp] -= avgY;
points[i] = Number(points[i].toFixed(2));
points[yp] = Number(points[yp].toFixed(2));
}
display("points array:");
display(points);
try{
var p:QuickObject = sim.addPoly({x:avgX, y:avgY, points:points});
p.userData.graphics.beginFill(0xFF0000);
p.userData.graphics.drawCircle(0,0,5);
}catch(e:*){
display("Invalid polygon data!");
}
poly.graphics.clear();
points = [];
}
This snippet shows the basic concepts needed to go about creating a polygon editor for QuickBox2D. I have an unreleased editor that I use for my QuickBox2D projects, at some point I may release it… but for now I figured I’d post this extremely simplified version for people to expand on.
Since the release of QuickBox2D 1.0 two bugs were discovered by numerous developers. The first bug was the inability to properly destroy group objects. The second bug was a small memory leak that caused most QuickObjects to remain in memory. Both of these bugs are now resolved.
Testing the memory leak. In QuickBox2D 1.0 if you created and destroyed 100s of rigid bodies, the ram would very slowly rise… Sometimes it would get garbage collected, but the memory would never fully be released. I created a simple test to make sure this is fixed in 1.1:
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this, {debug:false});
sim.createStageWalls();
var levelParts:Array = [];
const TWO_PI:Number = Math.PI * 2;
// destroys and then creates a bunch of rigid bodies
// called every second
buildRandomLevel();
setInterval(buildRandomLevel, 1000);
var txt:TextField = TextField(addChild(new TextField()));
txt.x = txt.y = 30;
txt.backgroundColor = 0xFFFFFF;
sim.start();
// display amount of ram used, to make sure garbage collection is working
sim.addEventListener(QuickBox2D.STEP, onStep);
function onStep(evt:Event):void{
txt.text = (System.totalMemory / 100000).toFixed(2) + "mb";
}
function buildRandomLevel():void{
// destroy all rigid bodies
for (var i:int = 0; i<levelParts.length; i++){
levelParts[i].destroy();
}
levelParts = [];
// create a bunch of circles and boxes
for (i = 0; i<16; i++){
var rad:Number = 0.4 ;
levelParts.push(sim.addCircle({x:1 + i * rad * 4, y : 2, radius:rad - Math.random()*0.3}));
var rot:Number = Math.random() * TWO_PI;
levelParts.push(sim.addBox({x:4+Math.random() * i * 2, y:4+Math.random()*i,
width:3, height:0.25, angle:rot, density:0}));
}
}
This snippet creates and destroys a bunch of rigid bodies again and again…. On my macbook 2.6 Ghz intel core duo… the ram runs between 79mb and 112mb. I let it run for 40 minutes and this did not change – it always eventually returned down to 79mb.
Well… while on the topic of skinning I figured I’d post something I’ve been meaning to post for awhile. Currently, joint skinning leaves something to be desired in QuickBox2D. This is because I haven’t had the need to skin many joints … and also because with joints like pulley, prismatic, revolute etc… I’m not entirely sure what the best skinning solution even is… For instance, on a pulley you probably don’t want three duplicate MovieClips used for the skin. Anyway, early on in my Box2D experimentation I needed distance joint skins so that feature has been around since maybe alpha 108…
It’s pretty simple, Check out the demo and code below:
import com.actionsnippet.qbox.*;
[SWF(width = 800, height = 600, backgroundColor = 0xFFFFFF, frameRate=60)]
var sim:QuickBox2D = new QuickBox2D(this, {debug:false});
sim.createStageWalls({fillColor:0xFFFFFF});
var circleA:QuickObject = sim.addCircle({x:3, y:3, radius:1, skin:CircleSkin});
var circleB:QuickObject = sim.addCircle({x:6, y:6, radius:0.5, skin:CircleSkin});
sim.addJoint({type:"distance", a:circleA.body, b:circleB.body, skin:JointSkin});
sim.start();
sim.mouseDrag();
I’ve been trying to finalize the way QuickBox2D skinning works… so that its flexible and so that I only add to the api rather than modifying it. So this post really has two main purposes… the first is to show you lots of skinning examples from complex to simple – and the second is to get feedback… I want suggestions regarding this – one of the reasons that Box2D allows you to manage skinning however you want is because there is no real general purpose solution for all cases. I designed QuickBox2D’s skinning based on my needs, but I’d like to refine it… and make it more flexible… so post your comments and complaints 😉
Bug Note
There was a bug in QuickBox2D 1.0 with skinning… I’ve updated the zip… so that this doesn’t break anyone’s projects… but I’ll also be zipping up QuickBox2D 1.1 and posting it late tonight… However in order to tweak these examples you’ll need to download this the new 1.0 zip.
Complex Skinning
Here is a demo showing the kind of stuff I use QuickBox2D for… I use lots of polygon rigid bodies so the skins are never scaled or anything… (I used my unreleased editor to generate the polygon data)
By default QuickBox2D will resize your skins to match your rigid bodies. There are times when this doesn’t make sense so I’ve added a new property to disable this. This demo shows circles that are automatically resized and one circle that has automatic skin resizing turned off (scaleSkin = false).
import com.actionsnippet.qbox.*;
stage.frameRate = 60;
var sim:QuickBox2D = new QuickBox2D(this, {debug:false});
sim.createStageWalls();
// QuickBox2D by default scales library skins
sim.addCircle({x:3, y:3, radius:2, skin:Xcircle});
sim.addCircle({x:6, y:3, radius:0.5, skin:Xcircle});
sim.addCircle({x:18, y:3, radius:1, skin:Xcircle});
// sometimes you may not want this behavior
// here the rays of the ToothSun skin are not part of the
// rigid body...
sim.setDefault({scaleSkin:false});
sim.addCircle({x:12, y:3, radius:73 / 60, skin:ToothSun});
sim.start();
sim.mouseDrag();
DisplayObject Skinning
This feature was requested by a few users. Basically it allows you to lay your DisplayObjects out on the stage… QuickBox2D reads their width, height, x, y and rotation values and adjusts the rigid body accordingly. If you specify width, height or radius in the params object then QuickBox2D will use that value – however currently setting x, y or angle in the params object will simply be ignored… as your basically defeating the purpose of using a DisplayObject skin. You can however set x, y and angle immediately after using one of the QuickBox2D creation methods… but really you should just use a library skin if you intend to set all the properties in ActionScript.
I think those few fla files cover most of the different ways you can do skinning in QuickBox2D. I may elaborate a bit in a future post or in the comments… I’d really appreciate any suggestions people have regarding this, so please post comments if you dislike something or find any bugs…
import com.actionsnippet.qbox.*;
import Box2D.Dynamics.*;
import Box2D.Collision.Shapes.*;
[SWF(width = 800, height = 600, backgroundColor = 0x222222, frameRate=60)]
var sim:QuickBox2D = new QuickBox2D(this, {debug:false});
var box:QuickObject = sim.addBox({x:12, y:16, width:3, height:3, density:0 , groupIndex:-1});
var circle:QuickObject = sim.addCircle({x:5, y:3, radius:0.5, groupIndex:-1});
// add another box to show that Box2D is still working
var littleBox:QuickObject = sim.addBox({x:12, y:3, width:1, height:1});
sim.createStageWalls();
sim.start();
sim.mouseDrag();
var filter:b2ContactFilter = new QuickContactFilter();
QuickContactFilter(filter).addGroupIndexCallback(onGroupNeg1, -1);
function onGroupNeg1(a:b2Shape, b:b2Shape):void{
//trace("group index -1 had a collision");
box.userData.alpha = 0.5;
setTimeout(function():void{ box.userData.alpha = 1 }, 200);
}
sim.w.SetContactFilter(filter);
This snippet answers a question from a recent comment. The question was basically: “Can you detect a collision between two rigid bodies that have the same negative groupIndex?”. When you give QuickObjects a negative groupIndex it means that they will not collide with one another. So by default Box2D contacts will not be triggered when these two rigid bodies overlap. In order to determine if these rigid bodies overlap you need to implement a custom b2ContactFilter class. This may sound confusing but its actually very easy. You can take a look at the custom b2ContactFilter class used in this snippet here: QuickContactFilter.as – It’s important to note that QuickContactFilter.as is not yet part of QuickBox2D, so if you want to run this snippet you’ll need to download the .as file.