Getting Started with Box2D Physics

The past few days I've been messing around with the Box2D physics engine. For someone who spends his days buried in business applications, this has been a fun bit of learning. Box2D has been ported to a ton of languages and I found a nice port to javascript called box2dweb.

First, let's look at a simple demo:

Click here for full jsFiddle

The first thing you'll need to do is set up a world and a loop to update it. The basics look like this:

var world = new b2World(
   new b2Vec2(0, 10), //gravity vector

    world.Step(1 / 60, 10, 10);

We just declared a world with some gravity. In the example above, we're applying gravity down, but you can have it pushing any direction you'd like. Next we set up an interval to run 60 times per second. Inside of that we tell the world to step 1/60th of a second while specifying the velocity and position iterations. For the velocity and positon iterations, the values can be altered to meet your needs. Lower will yield better performance, higher will yield better accuracy.

So, now you have a world with nothing in it. What fun is that? We'll need to add some stuff and start crashing it into each other.

There are two type of objects you can create. Static objects, like the triangle above, are fixed in the space. They are not affected by gravity or other objects. Dynamic objects are the fun ones that you get to move around. Our circles above are created and then nudged slightly to make them fall on either side of the triangle.


var fixDef = new b2FixtureDef;
fixDef.shape = new b2PolygonShape;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = .5;
    new b2Vec2(-1, 0),
    new b2Vec2(0, -1),
    new b2Vec2(1, 0)],3

var bodyDef = new b2BodyDef;
bodyDef.type = b2Body.b2_staticBody;    
bodyDef.position.Set(7, 7);


//Same fixture density, friction and restitution from above.
fixDef.shape = new b2CircleShape(.5);
var body=world.CreateBody(bodyDef);

I mentioned above that I'm nudging the circles. In order to push the shapes, we can use the ApplyImpulse method. It needs two parameters, a vector defining the force to be applied and a point that it should be applied to. Take a moment to go poke around in the fiddle and change the vector for the impulse. You can do some fun stuff like punch them straight up in the air. Go ahead, I'll wait.

There is one last bit you'll need to get your own samples going. All of the code we've done above describes the objects and their interactions. We still need a way to visualize it though. Luckily box2dweb has a debug drawing mode to render the objects on a canvas element. Here's what you need to set it up:

var debugDraw = new b2DebugDraw();

With that, all that is left is to call world.DrawDebugData() right after you step. Now we can see our demolition derby in action!

I think that covers the basics. There is a lot of fun things you can do with the sample. Try changing the restitution (bounciness), the force of gravity, the direction of gravity, which direction you "nudge" the falling circles... heck, just start changing stuff and watch. It's way more fun than it should be.

Knockout.js Observable Extensions

This started out as a post about how to implement the new extender feature in Knockout.js 2.0. I wanted to see how well that would improve the experience of a money observable I created several months back. Once I had it implemented though, I was a bit disappointed. My extender doesn't have any arguments, but the knockout observable extend call only accepts a hash in the form of {extenderName:extenderOptions}. I ended up with a call that looked like this: var cash=ko.observable(5.23).extend({money:null});

That didn't leave a very good taste in my mouth. So, I pulled down knockout and set out to change the way the extenders were implemented. I've grown fond of how jQuery chaining worked, so why not bring that to Knockout's observables? Luckily Ryan Niemeyer was there to save me from myself and pointed out that I could just extend ko.subscribable.fn to achieve the desired effect.

I'm happy with the outcome. Let's explore the strategy a bit. Before I get in too deep, here's the end result:

Click here for full jsFiddle

You may be asking yourself, "What's so great about this?" This is basically the same as my previous sample with one exception. This implementation attaches directly to the subscribable type that KO provides. You might not have seen this unless you've spent some time digging around the knockout.js source. This type serves as a base for observables, obervableArrays and dependentObservables computed observables.

Here's the code that provides the money formatting:

    var format = function(value) {
        toks = value.toFixed(2).replace('-', '').split('.');
        var display = '$' + $.map(toks[0].split('').reverse(), function(elm, i) {
            return [(i % 3 === 0 && i > 0 ? ',' : ''), elm];
        }).reverse().join('') + '.' + toks[1];

        return value < 0 ? '(' + display + ')' : display;
    }; = function() {
        var target = this;
        var writeTarget = function(value) {
            target(parseFloat(value.replace(/[^0-9.-]/g, '')));
        var result = ko.computed({
            read: function() {
                return target();
            write: writeTarget

        result.formatted = ko.computed({
            read: function() {
                return format(target());
            write: writeTarget

        return result;

Line 11 is where we start. By extending the subscribable.fn object we are adding a property to each and every subscriabable object that KO creates for us. This will give us the ability to chain observables to one another as long as we return an observable from our method(line 32).

On line 12 we see that 'this' references the observable we're extending. I like this because there are no special method signatures we need to implement. Here I'm just grabbing my own reference of this as a variable named target.

Line 18 is where this starts to get a little interesting. I'm creating a writable computed observable that will return the value from the base observable when read. When it gets written to, it will sanitize the input and then write that to the base observable. This will be the observable we return for public consumption(line 32).

Line 25 is where the formatting comes into play. To the observable we're returning we'll add another observable as a property named 'formatted'. This is what we'll bind to whenever we want to see a pretty version of our value. This is another read/write computed observable like we did above. When the property is read from, it will pass the base observable's value through a formatter. The write is the same as the base observable.

Use It

var viewModel = {
    Cash: ko.observable(-1234.56).money(),
    Check: ko.observable(2000).money(),
    showJSON: function() {

viewModel.Total = ko.computed(function() {
    return this.Cash() + this.Check();
}, viewModel).money();

On lines 2,3, and 11 you can see where I've used the observable extension I created above. The cool thing about this technique is that we don't care what kind of observable we're extending, it just works.

The showJSON function on line 4 is what gets fired when we click the "Show View Model JSON" button on the example above. Click this and you will see that our json serialization is clean. This is because the base observable we return is the unformatted (no dollar signs, commas, or parenthesis) version.

The Payoff

<div class='ui-widget-content'>
        <label>How much in Cash?</label>
        <input data-bind="value:Cash.formatted,css:{negative:Cash()<0}" />
        <label>How much in Checks?</label>
        <input data-bind="value:Check.formatted,css:{negative:Check()<0}" />
        <span data-bind="text:Total.formatted,css:{negative:Total()<0}" />
        <button data-bind="click:showJSON">Show View Model JSON

Lines 4 and 8 we've bound the input's value to the formatted version of the extended observable. Line 12 has the text of a span bound to the formatted version of the computed observable.

I've rehashed this example 3 times now, but I'm happiest with this implementation. Extending *.fn.* isn't documented anywhere I saw, but maybe it should be. 😉 Maybe I should RTFM, it's clearly documented here. This chaining technique will be familiar to anyone who has used jQuery. What do you think about this technique?

Cross posted from Fresh Brewed Code. If you haven't taken a look over there, please take a moment to see what we've been up to.

Knockout.js Money Observable

A few days ago I posted a solution to create a custom money binding for knockout.js. If you recall, I was a bit hesitant about the solution because I felt that it wasn't very semantic. Namely, DOM objects do not have a money property to bind to. I had a chat with Elijah Manor and he shared the same reservations. Comments on that post echoed the yucky feeling. Time for round 2.

See the full sample on jsFiddle

What I had missed was the writable dependentObservable introduced in knockout.js some time recently. With this new found power I can keep the appropriate text or value bindings and still have a clean view model. With the solution above, I don't have to jump through hoops to get a clean json representation of my view model. On top of that, my bindings are still simple enough to understand. There is less magic and I like it that way.

This feels a lot better than the first solution. I'm still not sold though. It feels like this type of concern should be pushed out of the view model. Possibly something like this? <input data-bind="value:Cash" data-convert="value:MoneyConverter" />

What do you think of the new bits? Is this a better or worse solution? Also, how can we improve this?

Knockout.js Custom Money Binding

EDIT: I think I've found a better solution. Click here to see the post on creating a money observable.

As I've been digging deeper into knockout.js, I had a need to simplify some things. I needed to have my view model hold float values but display it as a formatted money value. Time to write my own custom binding for knockout.

I'm a bit mixed about this. On one hand, it was dead simple to get the behavior I needed. On the other, the semantics don't match up. The built in bindings are things like text and value. That is, you are mating an object to the text or value property of a DOM element. DOM elements don't have a 'money' property, which makes this approach feel wrong.

There it is and I'm not confident that I'm using the tool appropriately. What do you think?

Playing With Knockout.js

When I was in grade school we used to do these fun run things. Basically, we begged all of our family to give us money for every lap run. Then we would go run on the hot blacktop for 30 minutes. In exchange for all of this we were able to get stupid ribbons and prizes. It was anything but fun.

I'm not sure why this example popped into my head when it came time to create an example to show off the simplicity and power of Knockout.js. Regardless, it did and you can see the result below.

I like this example because it shows bindings to a couple of input types. The lap count at the top is multiplied by the Pledge Per Lap in each row. The values are summed across each row and down the columns.

Once you've played with my silly example, click on the html and js tabs and let the simplicity soak in. There is almost no code there. I didn't have to handle change and click events. I didn't need to do anything special when a row gets added to recalculate totals. Even the empty grid message was a snap, look at that easy visible binding! It. Just. Works.

What are you waiting for? Go read more about Knockout.js now.

Next Page »