Browse the notebook

Tag: QuickBox2D

QuickBox2D Editor

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.

Take a look at the editor

Download the Source

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.

Read snippet: QuickBox2D Editor

To release or not to release…

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.

Thoughts? Should I release it anyway?

Read snippet: To release or not to release…

Polygon Problems

Lots of people have mentioned that they have problems with QuickBox2D Polygons. The simple solution is not to use the verts 2d array (which is more like how Box2D does polys). So when in doubt about polygons, simply use the points array which will nearly always work as long as the contour you define does not cross over itself. Here is a simple example on wonderfl:

flash on 2010-3-6 – wonderfl build flash online

Also… polygons are covered extensively in part two of the tutorial over at active tuts… more on that later.

Here is the timeline code:

import com.actionsnippet.qbox.*;
			/*
			   0
			  / 
			 0_0 0
			   | |
			   0-0 
			*/
			var sim:QuickBox2D = new QuickBox2D(this);
			sim.createStageWalls();
			// define the contour of your poly
			// no limits as long as it doesn't cross over
			// itself
			sim.addPoly({x:10, y:5, points:[0.5,0,
											1, 1,
											1, 2,
											0.5, 2,
											0.5, 1,
											0,1,
											0.5,0],
											wireframe:false});
			sim.addCircle({x:11, y:10});
			sim.start();
			sim.mouseDrag();
Read snippet: Polygon Problems

QuickBox2D Mini-Poly Editor

[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.


Have a look at the swf here…

Read snippet: QuickBox2D Mini-Poly Editor

QuickBox2D Custom Debug Draw

import com.actionsnippet.qbox.*;
import Box2D.Dynamics.*

stage.frameRate = 60;

var sim:QuickBox2D = new QuickBox2D(this, {debug:true});

// get at the b2DebugDraw instance
var debug:b2DebugDraw = sim.w.m_debugDraw;
debug.m_drawScale = 30.0;
debug.m_fillAlpha = 0.5;
debug.m_alpha = 0.5;
debug.m_lineThickness = 1.0;
debug.m_drawFlags = 0xFF;

sim.createStageWalls();  

for (var i:int = 0; i<10; i++){
  sim.addBox({x:3 + i, y:3 + i, width:2, height:0.5});
}
sim.addCircle({x:12, y:5, radius:2});

sim.start();
sim.mouseDrag();

Note: This snippet requires the QuickBox2D library

This snippet shows an easy way to get at the settings for Box2D’s debug renderer.


Have a look at the swf…

Read snippet: QuickBox2D Custom Debug Draw

QuickBox2D 1.1 (2 major bug fixes)

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.

Download QuickBox2D 1.1

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.


Have a look at the swf…

Thanks to all the people who gave feedback that lead to the discover of these bugs.

Read snippet: QuickBox2D 1.1 (2 major bug fixes)

QuickBox2D Mini-Machine

Since this is a rather large snippet check out this demo first:

View Demo…

and here is the source:

import com.actionsnippet.qbox.*
import Box2D.Collision.Shapes.*;
import Box2D.Common.Math.*;

[SWF(width = 800, height = 600, backgroundColor = 0x000000, frameRate = 60)]

var sim:QuickBox2D = new QuickBox2D(this, {debug:true});
 
var sw:Number = stage.stageWidth / 30;
var sh:Number = stage.stageHeight / 30;
			
sim.addBox({x:sw / 2, y:sh, width:sw - 3, height:1,  density:.0})
sim.addBox({x:sw / 2, y:0, width:sw - 3, height:1,  density:.0 })
sim.addBox({x:0, y:sh / 2, width:1, height:sh ,  density:.0})  
sim.addBox({x:sw, y:sh / 2, width:1, height:sh,  density:.0})  

var slider:QuickObject = sim.addBox({x:3, y:6, width:6, height:0.25, density:0, angle:0.05});
var pusher:QuickObject = sim.addBox({x:15, y:18, width:4, height:4, density:0});

sim.setDefault({collideConnected:false, frequencyHz:10});
var anchor:QuickObject = sim.addCircle({x:3, y:2, radius:0.2, density:0});

var m0:QuickObject = sim.addBox({x:3, y:5, width:1, height:0.25, fixedRotation:true});

var j0:QuickObject = sim.addJoint({type:"distance", a:anchor.body, b:m0.body});

var m1:QuickObject = sim.addBox({x:2.5, y:9.5, width:0.25, height:6, fixedRotation:true});
var m2:QuickObject = sim.addBox({x:3.5, y:9.5, width:0.25, height:6, fixedRotation:true});

var j1:QuickObject = sim.addJoint({type:"distance", a:m0.body, b:m1.body});
var j2:QuickObject = sim.addJoint({type:"distance", a:m0.body, b:m2.body});
var j3:QuickObject = sim.addJoint({type:"distance", a:m2.body, b:m1.body});

var boxes:Array = [];
var boxNum:int = 21;
var index:int = boxNum;
var filter:b2FilterData;
var lookupQuickObject:Dictionary = new Dictionary();
for (var i:int = 0; i<boxNum; i++){
	boxes[i] = sim.addBox({x:3, y:6.3 + i * 0.3, width:0.6, height:0.3,  friction:0.0, allowSleep:false});
	lookupQuickObject[boxes[i].shape] = boxes[i];
}

var m3:QuickObject = sim.addBox({x:3, y:12.25 , width:1, height:0.25, allowSleep:false,fixedRotation:true, groupIndex:-1});

var j4:QuickObject = sim.addJoint({type:"revolute", a:m1.body, b:m3.body});
var j5:QuickObject = sim.addJoint({type:"revolute", a:m2.body, b:m3.body});

var t:Number = Math.PI;
var dropBox:int = 0;
var prevBox:QuickObject;
var resetVec:b2Vec2 = new b2Vec2(0,0);

function setGroupIndex(b:QuickObject, index:int):void{
	filter = b.shape.GetFilterData();
	filter.groupIndex = index;
	b.shape.SetFilterData(filter);
}

sim.start();
sim.addEventListener(QuickBox2D.STEP, onStep);
function onStep(evt:Event):void{
	dropBox++;
	
	if (dropBox % 80 == 0){
		index--;
		if (index > -1){
			if (prevBox){
				setGroupIndex(prevBox, 1);
			}
			prevBox = boxes[index]
			setGroupIndex(boxes[index], -1);
			m3.y += 0.05;
		}
	}
	
	if (index < 0){
		if (pusher.x > 3.5){
			pusher.x -= 0.05;
		}
	}
	for (var i:int = 0; i<boxNum; i++){
		if (boxes[i].y > 22){
			boxes[i].angle = 0;
			boxes[i].y = -2;
			boxes[i].x = 1;
			boxes[i].body.SetLinearVelocity(resetVec);
		}
	}
	
	if (index > 0){
	  anchor.x = 6 + 3 * Math.cos(t);
	  t += 0.01;
	}
}
Read snippet: QuickBox2D Mini-Machine

QuickBox2D Joint Skinning

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();


Check out the swf here…

Download the fla here…

Read snippet: QuickBox2D Joint Skinning