Running Box2D on server with Node.js via

I was kinda bored from the TV this friday and decided that learning a little more on Node.js was more fun. Once able to run a “Hello World” example, I wanted to advance into working on websockets using Socket.IO. Socket.IO is a library for both browser and server which simplifies working with websockets, and at the same time provides fallbacks for older browsers. It was really easy to get started, sending messages between browser and server after short peek into the docs & examples.

Next step was mixing it all up and adding my favorite js library – Box2D.js! I took the code from my Box2D DOM demo in to the main file and created a module from Box2D, exposed  via module.exports. And shockingly the backend-to-frontend-port worked on (almost) the first run! So now instead of the browser animates it’s own DOM objects via JS, it receives CSS for all objects at 30fps from server!

4 browsers, 2 iPhones and 1 iPad, with a lot of boxes animated in sync:

You can download the source here. . All needed libs are embedded, just run ‘node box2dserver.js’ and host the same folder on your localhost. Also remember to change the ‘host’ address in index.html to the one running Node:

window.socket = io.connect('http://<node-server-IP-or-name-here>:8080');

Animating a webpage with Box2d physics

Now this is what I call responsive design :-)

Now this is what I call responsive design!

You may have seen fun projects/demoes where a webpage is demolished using lifelike physics animations. Wario Land Shake It is a good example of that and it’s also allows the user to drag page elements around after the video is done playing. This however is created as a full page Flash, trying to look like a HTML page. Similar cases has also been done just by pre-rendering all into a video. So I wanted to have a go at doing this in HTML, as I haven’t seen that done before.

Continuing on what I learned creating my previous post about Box2d for JavaScript, I wanted to take it a step further replacing the debug renderer with elements from a webpage. The elements should be working as a blue print for the Box2d objects, and the transformation into the physics world should be transparent. I created a quick webpage using <div> elements with some mockup content and started on the steps to make it work:

  1. Scan the appropriate part of a webpage for <div> elements, creating the corresponding counterparts in the Box2d world. This turned out to be pretty straight forward, using a jQuery selector with the each() method looping through and creating boxes in Box2D. Positions and dimensions were extracted from CSS, being absolute positioned for the sake of simplicity. After they where reset to a 0,0 position, ready for letting the animation engine handle the positions later. A reference to the <div> was injected into the m_userdata of each of the Box2d bodies.
  2. Animating is done by looping through all fixtures within the bodies in the Box2d world, retrieving the position and rotation of the objects. Thus having rotation of the boxes, just using god ol’ top & left for positioning and animating had to be forfeit. Instead we use the transform property on CSS3, offsetting the position from 0,0 and setting the correct rotation. An added super bonus is setting transform: translateZ(0) in the parent element, we get super fast GPU accelerated animation. Using the -webkit vendor prefix, we even get pretty decent performance on iOS devices.
  3. Checking that all was in a 1:1 relationship between the browser rendering of the <div> elements and it’s Box2d counterparts also had to be done. I did this by using the debug renderer on a canvas, being displayed behind the elements. In the example you can turn it on and off, also making the <div> elements transparent to see both “worlds” at the same time.
  4. Handling both mouse and touch events is always a bit of a chore when you just want to focus at the task at hand. So I wrote my first Javascript tool ever, MouseAndTouch.js that handles both types of input in your typical “press-draw-up-end” manner. The code setup is probably not quite kosher, but writing it helped me along the way of learning JavaScript.

Ok, thats quite enough talk already. Go ahead and take it for a spin! Make sure that you drag the elements after they have been dropped :-) And please comment, esp. on my novice setup on the MouseAndTouch.js as a standalone tool.

For those of you that like more technical details, here are some things I found in the development process:

  • The rotate() method of CSS3 transform does not like negative values or infinite number of decimals. So you need to normalize the angle and fix the number of decimals. I ended up specifying the angle with degrees and setting the number of decimals to two.
  • Creating some shorthand methods for creating Box2d items helps speed up the development process.

A quick snapshot of the mobile friendly internet

You need the patience of a sniper to read thisI’m just home from my daily commute on the train, which also happens to be my favorite type of transport. It’s also a place where I can take some time to catch up on my never ending list of posts to read on Reeder, Twitter and Instapaper. The latter I have promised myself to have all articles read a couple years into my retirement.

Today my Twitter feed was full of references to the upcoming OSX Mountain Lion which is due for release this summer. Tech interested bloke as I am, I had to get information directly from the source itself; the new pages put on on the Apple website. However it was a sharp contrast coming from the sweet mobile apps with readable text, to a static “old school” 980px website rendered on a iPhone display. Retina display makes the text sharper, but the 4S not being bundled with a magnifying glass it’s still impossible to read the text. Zoom you say? Double tapping the 700px text columns still didn’t do the trick, forcing me to to the go in to “Sniper mode” reading the text. An experience reminding me more scouting for enemies (camping) in Battlefield with a 8x ballistic scope, than a good reading experience.

For marked a leading player on mobile like Apple, you ought to think that zooming webpages should be a thing of the past. But but for the sake of being fair here, I have taken some photos and created a photo gallery titled “A quick snapshot of the mobile friendly internet”:

Playing with Box2D in Javascript

Box2D is probably one of my favorite libraries in whole of the programming world, simulating physics in a realistic manner. Actually you may already have played with it without knowing, just by playing Angry BIrds. There it handles collisions between flying birds and their nemesis; the pigs and their fragile buildings.

I’ve used Box2D for a scene in my last project at Apt; the Norwegian site for the Volkswagen Beetle. As one of the scenes is a “tribute” to Line Rider (a classic Flash game with physics simulation), I choose to use the renowned Box2D on this occasion.

Click to play!This particular evening I focused on testing a js port of Box2D, namely the Box2D-Web as it was recommended on the Creative JS blog. This port is actually an automatic conversion of the Actionscript one, so I also expected that reuse of my code from the Flash VW project would be a trival. This turned out to be a truth with some modifications, as some adjustment was needed. I also used the bundled “debug renderer” which is really handy in development when you create Box2D objects and need to look at how they act. In a normal development process of games and such, you normally exchange the debug renderer with animation of your own graphics. But in this lab experiment I choose to keep it for simplicity and its clean appearance.

Enough talk, take a look at it here and play with it. First draw/touch a hill from top left corner towards the bottom right, then drop a circle (or twenty).

PS. If you are a developer and a would like to learn more about Box2D, start with reading the manual regardless of your desired programming language. You should at least need to learn some of the basic terms and the theory, before getting down and dirty with the code. The next vise step is to pick a port for your chosen programming language, and find some tutorials and examples to get you started.



A shot at installing WordPress

I’m not really sure if this is to be a start of my blog, or me just being curious on WordPress. Either way it will be a place where I post more permanent links to stuff that I’m working on than just using Twitter. I would also like to get some more experience writing, as it is an area I’m less confident in.