Recently I presented a small Qt 4.6 based demo on the LinuxTag in Berlin, as an example of something you could do with the Nokia Qt SDK. It combined existing projects like the Tiled map editor and the Box2D physics library with Qt Mobility’s sensors API for reading out the accelerometer. It looks like this on the N900:
Andreas has demonstrated before that integrating Box2D and QGraphicsView is easy. In this demo I have used the generic object layer support in the Tiled map editor to conveniently define the starting points and properties of some boxes, including the definition of the colliding parts of the rather minimal tile based background.
The big red boxes around the sides are a quick hack to prevent any of the dynamic boxes from leaving the scene. Since indeed, turning your device will change the gravity applied to the boxes as appropriate. This was the first time I’ve used an accelerometer and I expected it to be somewhat more complicated, but combining the sensors API in Qt Mobility with Box2D was as easy as:
QAccelerometerReading *reading = mAccelerometer->reading(); b2Vec2 gravity(-reading->x(), -reading->y()); mWorld->SetGravity(gravity);
As documented, the accelerometer gives us the force applied to the device relative to freefall. When the device is in rest, this is the exact opposite of the applied gravitational force. Hence we have to reverse the x and y readings when turning them into the gravitational force applied to the Box2D world. One little caveat: as of Qt Mobility 1.0 the application will need to run as root on the N900 to be able to get any values out of the accelerometer. This is bug QTMOBILITY-326.
Here is the demo in action:
The complete sources of this demo are available on gitorious.org, on the ‘qtarcade’ branch. The repository includes the necessary classes from Tiled and Box2D so that it’s easy to try it out.
With Qt Creator 2.0 and the Nokia Qt SDK 1.0 released last week, it could not be easier to start hacking and implement your own crazy ideas. Who will be the first to get his cool Qt app signed for free and distributed on the Ovi store?